PostgreSQL 如何从分组计数列取最大值以查询风险最高城市
方案1:仅返回1个最高风险城市(无并列场景适用)
直接对统计结果按高风险人数倒序排序,取第一条即可:
select p.city, count(p.state_of_health) as high_risk_count from public."Person" p where p.state_of_health = true group by p.city order by high_risk_count desc limit 1;
如果存在多个城市高风险人数同为最大值,该语句只会返回其中一条记录。
方案2:返回所有并列最高风险城市(通用场景推荐)
用RANK()窗口函数实现,人数相同的城市排名一致,能把所有最高风险的城市全部查询出来:
with city_risk_stats as ( select p.city, count(p.state_of_health) as high_risk_count, rank() over (order by count(p.state_of_health) desc) as risk_rank from public."Person" p where p.state_of_health = true group by p.city ) select city, high_risk_count from city_risk_stats where risk_rank = 1;
内容的提问来源于stack exchange,提问作者AssSoonAsPossiblee
相关产品推荐
相关产品推荐

