【问题标题】:Is possible to get the percentage value on query using count and group by?是否可以使用 count 和 group by 获取查询的百分比值?
【发布时间】:2021-07-08 16:33:42
【问题描述】:

我有一个问题:

select no_tipo_origem, 
       count(*) total 
from table 
group by no_tipo_origem

结果是:

tipo 1 |  25
tipo 2 | 133
tipo 3 |  48

我需要这样计算百分比:

tipo 1 |  25 | 12.1
tipo 2 | 133 | 64.5
tipo 3 |  48 | 23.3

【问题讨论】:

    标签: postgresql count sum window-functions percentage


    【解决方案1】:

    将每个总数除以您可以使用SUM() 窗口函数获得的所有总数的总和:

    select no_tipo_origem, 
           count(*) total,
           round(100.0 * count(*) / sum(count(*)) over (), 1) percentage 
    from tablename 
    group by no_tipo_origem
    order by no_tipo_origem
    

    查看简化的demo

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      相关资源
      最近更新 更多