psql,显示不在group by子句中的列
psql, display column that is not in the group by clause
我在查询时遇到问题。我有两个表:国家和城市,我想显示每个国家/地区人口最多的城市。
查询如下:
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;`
错误
column "city.name" must appear in the GROUP BY clause or be used in an aggregate function.
我不知道如何解决这个问题,我尝试进行子查询但没有成功。
我怎样才能让它工作?
您可以使用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
我在查询时遇到问题。我有两个表:国家和城市,我想显示每个国家/地区人口最多的城市。
查询如下:
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;`
错误
column "city.name" must appear in the GROUP BY clause or be used in an aggregate function.
我不知道如何解决这个问题,我尝试进行子查询但没有成功。 我怎样才能让它工作?
您可以使用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