【问题标题】:To calculate percentage value计算百分比值
【发布时间】:2015-10-11 17:57:33
【问题描述】:

我有如下数据..

count              ID
----------------------
10                 1
20                 2
30                 4

如何在 oracle 中实现计算百分比的第三列。

count              ID   %
-------------------------------------
10                 1    10/(10+20+30)
20                 2    20/(10+20+30)
30                 4    30/(10+20+30)

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:

    使用RATIO_TO_REPORT

    SQL Fiddle

    查询

    with your_table(count_, id_) as (
      select 10,1 from dual union all
      select 20,2 from dual union all
      select 30,4 from dual
      )
    select count_, id_,
    ratio_to_report(count_) over () as percentage
    from your_table
    

    Results

    | COUNT_ | ID_ |          PERCENTAGE |
    |--------|-----|---------------------|
    |     10 |   1 | 0.16666666666666666 |
    |     20 |   2 |  0.3333333333333333 |
    |     30 |   4 |                 0.5 |
    

    【讨论】:

      【解决方案2】:
      SELECT id, count, ( count / ( SELECT SUM(count) FROM table) * 100 ) as per FROM table GROUP BY id
      

      【讨论】:

      • 如果你只想要 value/sumofvalue,你可以去掉乘法 100
      【解决方案3】:

      窗口函数为此类问题提供了最佳解决方案。您试图实现的是在表的一个查询中实现两个级别的聚合。

      select id
            ,count(*)
            ,sum(count(*)) over () as CountOfAll
            ,(1.0 * count(*)) / sum(count(*)) over () as Pct
      from some_table
      group by id
      

      在分母可能导致零的情况下,您必须将 Pct 计算包装在 CASE 语句中以避免除以零错误:

      select id
        ,count(*)
        ,sum(count(*)) over () as CountOfAll
        ,case when sum(count(*)) over () = 0 
            then 0 
            else (1.0 * count(*)) / sum(count(*)) over () 
         end as Pct
      from some_table
      group by id
      

      窗口函数为在单个查询中创建聚合结果提供了更多可能性,并且是一个值得添加到 SQL 工具带中的工具!

      【讨论】:

        猜你喜欢
        • 2018-04-19
        • 2011-06-01
        • 2021-01-10
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多