使用以下数据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 ID
和MAX(DESC)
也包括County
。
查询的结果是:
1 UK 200
2 NZ 250
答案 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 )