2021年4月24日星期六

LIMIT by distinct values in PostgreSQL

I have a table of contacts with phone numbers similar to this:

Name    Phone  Alice   11  Alice   33  Bob     22  Bob     44  Charlie 12  Charlie 55  

I can't figure out how to query such a table with LIMITing the rows not just by plain count but by distinct names. For example, if I had a magic LIMIT_BY clause, it would work like this:

SELECT * FROM "Contacts" ORDER BY "Phone" LIMIT_BY("Name") 1    Alice 11  Alice 33  -- ^ only the first contact      SELECT * FROM "Contacts" ORDER BY "Phone" LIMIT_BY("Name") 2    Alice   11  Charlie 12  Alice   33  Charlie 55  -- ^ now with Charlie because his phone 12 goes right after 11. Bob isn't here because he's third, beyond the limit  

How could I achieve this result?

https://stackoverflow.com/questions/67248525/limit-by-distinct-values-in-postgresql April 25, 2021 at 08:03AM

没有评论:

发表评论