psql,显示不在group by子句中的列

时间:2015-12-11 16:17:21

标签: postgresql join aggregation

我遇到查询问题。我有两张桌子:国家和城市,我希望展示每个国家人口最多的城市。

以下是查询:

select country.name as coname, city.name as ciname, max(city.population) as pop 
    from city 
    join country on city.countrycode=country.code 
    group by country.name 
    order by pop;`

错误

  

列“city.name”必须出现在GROUP BY子句中,或者用于聚合函数。

我不知道如何解决这个问题,我试图制作一个子查询,但它没有成功。 我怎样才能使它工作?

1 个答案:

答案 0 :(得分:1)

您可以使用 rank 功能轻松获取该功能:

select * from
(
select country.name as coname, 
 city.name as ciname, 
 city.population, 
 rank() over (partition by country.name order by city.population desc) as ranking 
from 
    city 
join 
    country 
on city.countrycode=country.code 
 ) A
 where ranking = 1
相关问题