You need to enable JavaScript to run this app. PostgreSQL 如何从分组计数列取最大值以查询风险最高城市
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 16:06:03