【问题标题】:Percentage with condition SQL带有条件 SQL 的百分比
【发布时间】:2021-08-06 16:00:40
【问题描述】:

假设我有一个包含 ID、NAME、POPULATION 列的简单表 CITY 我想知道人口> 10000的城市的百分比是多少。 我可以做到这一点

select count(*) / (select count(*) from CITY) * 100
from CITY
where population > 10000 

或者像这样

select count(case when population > 100000 then 1 else null end) / count(*) * 100
from CITY

但我认为为此使用窗口函数是合适的。如何? 当我做类似的事情时

select count(*) / sum(count(*)) over () * 100
from CITY
where population > 100000

我得到 100 个原因 over() 只计算剩余的行。所以,问题是: 如何实现一个widow函数来计算有条件的百分比?

【问题讨论】:

    标签: sql conditional-statements window percentage


    【解决方案1】:

    您不需要窗口函数。最简单的方法使用AVG()

    select avg(case when population > 10000 then 100.0 else 0 end) as percentage
    from CITY;
    

    当您想保留数据集中的原始行时,窗口函数是合适的。当你想总结它们时,聚合就是你想要的——在这种情况下,条件聚合利用case 表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      相关资源
      最近更新 更多