PostgreSQL选择max with group by和附加值

时间:2015-05-20 14:20:43

标签: sql postgresql group-by

使用以下数据from a SELECT * FROM (SELECT...) AS foo

ID    Country   Area
1     US        100
1     UK        200
2     AU        150
2     NZ        250

如何按ID选择热门区域和国家/地区?所以GROUP BY IDMAX(DESC)也包括County

查询的结果是:

1     UK     200
2     NZ     250

2 个答案:

答案 0 :(得分:4)

SELECT DISTINCT ON (ID)
       ID, Country, Area
FROM   foo
ORDER  BY ID, Area DESC NULLS LAST;

详细解释和特殊情况的更快替代方案的链接:

答案 1 :(得分:2)

试试这个

select ID,Country,Area
from (SELECT...) AS foo
WHERE Area = (SELECT MAX(Area)
              FROM (SELECT...) AS foo2
              WHERE foo.ID = foo2.ID )