我有如下數據..要計算百分比值
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)
我有如下數據..要計算百分比值
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)
SELECT id, count, (count/(SELECT SUM(count) FROM table) * 100) as per FROM table GROUP BY id
查詢:
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
在情況下,分母可能導致零,你必須包裝在一個CASE語句的PCT計算零個誤差,避免分裂:
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 –