计算百分比值

时间:2015-07-22 03:24:35

标签: sql oracle oracle11g

我的数据如下..

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)

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

SELECT id, count, ( count / ( SELECT SUM(count) FROM table) * 100 ) as per FROM table GROUP BY id

答案 2 :(得分:0)

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

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工具带的工具!