【问题标题】:psql, display column that is not in the group by clausepsql,显示不在group by子句中的列
【发布时间】:2016-03-17 15:02:18
【问题描述】:

我在查询时遇到问题。我有两张表:国家和城市,我想显示每个国家人口最多的城市。

这是查询:

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 子句中或用于聚合函数中。

我不知道如何解决这个问题,我尝试进行子查询但没有成功。 我怎样才能让它工作?

【问题讨论】:

  • 要解决您的错误,您必须将city.name 添加到group by。但我不知道它是否会给你正确的结果,你必须显示两个表的定义,以及一些数据样本
  • 如果我将 city.name 添加到组中,它将显示一个国家的所有城市
  • 您可以轻松使用:rank窗口函数来获取它

标签: postgresql join aggregation


【解决方案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

【讨论】:

  • 谢谢这个工作,第四列“排名”是什么意思?
  • 它是一个计算列(ranking 只是一个别名),它根据人口给出国家城市的排名。详情请查看文档
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2015-12-18
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多