Sql 计算百分比值

Sql 计算百分比值,sql,oracle,oracle11g,Sql,Oracle,Oracle11g,我有如下数据 count ID ---------------------- 10 1 20 2 30 4 如何实现oracle中计算百分比的第三列 count ID % ------------------------------------- 10 1 10/(10+20+30) 20

我有如下数据

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)
使用

查询

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
| COUNT_ | ID_ |          PERCENTAGE |
|--------|-----|---------------------|
|     10 |   1 | 0.16666666666666666 |
|     20 |   2 |  0.3333333333333333 |
|     30 |   4 |                 0.5 |

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
| COUNT_ | ID_ |          PERCENTAGE |
|--------|-----|---------------------|
|     10 |   1 | 0.16666666666666666 |
|     20 |   2 |  0.3333333333333333 |
|     30 |   4 |                 0.5 |

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

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工具中的工具

如果只需要value/sumofvalue,可以删除乘法100