PostgreSQL select max with group by and additional value
本问题已经有最佳答案,请猛点这里访问。
使用以下数据
1 2 3 4 5 | ID Country Area 1 US 100 1 UK 200 2 AU 150 2 NZ 250 |
如何通过
查询的结果将是:
1 2 | 1 UK 200 2 NZ 250 |
1 2 3 4 | SELECT DISTINCT ON (ID) ID, Country, Area FROM foo ORDER BY ID, Area DESC NULLS LAST; |
有关特殊情况的更快替代方案的详细说明和链接:
- 选择每个GROUP BY组中的第一行?
试试这个
1 2 3 4 5 | SELECT ID,Country,Area FROM (SELECT...) AS foo WHERE Area = (SELECT MAX(Area) FROM (SELECT...) AS foo2 WHERE foo.ID = foo2.ID ) |