PostgreSQL select max with group by and additional value [duplicate]

我只是一个虾纸丫 提交于 2020-12-09 06:53:33

问题


With the following data from a SELECT * FROM (SELECT...) AS foo:

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

how can you select the top area and country by ID? So GROUP BY ID and MAX(DESC) but also include the County.

The the result of the query would be:

1     UK     200
2     NZ     250

回答1:


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

Detailed explanation and links to faster alternatives for special cases:

  • Select first row in each GROUP BY group?



回答2:


Try this

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


来源:https://stackoverflow.com/questions/30352438/postgresql-select-max-with-group-by-and-additional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!