如何在数据透视语句中包含百分比计算
Posted
技术标签:
【中文标题】如何在数据透视语句中包含百分比计算【英文标题】:How to include percent calculations in pivot statement 【发布时间】:2020-01-29 18:34:35 【问题描述】:使用数据透视语句,我可以按标题分解数据表中的计数:
select * from (
select * from ta
)
pivot (
COUNT(title)
for title in ( 'worker', 'manager') )
所以结果是这样的:
STATUS 'worker' 'manager'
started 3 1
finished 4 5
ready 3 4
我需要添加的是百分比,即
STATUS 'worker' percent 'manager' percent
started 3 30% 1 10%
finished 4 40% 5 50%
ready 3 30% 4 40%
知道如何在同一个语句中完成此操作吗? 见http://sqlfiddle.com/#!4/e6c04a/1/0
【问题讨论】:
【参考方案1】:而不是使用条件聚合,您可以使用 -
select STATUS
,WORKER
,WORKER/SUM(WORKER) OVER()*100 percent
,MANAGER
,MANAGER/SUM(MANAGER) OVER()*100 percent
from (
select * from ta
)
pivot (
COUNT(title)
for title in ( 'worker' AS WORKER, 'manager' AS MANAGER))
Here 是演示。
【讨论】:
【参考方案2】:使用条件聚合和窗口函数:
select status,
sum(case when title = 'worker' then 1 else 0 end) as worker,
sum(case when title = 'manager' then 1 else 0 end) as manager,
(sum(case when title = 'worker' then 1 else 0 end) /
sum(sum(case when title = 'worker' then 1 else 0 end)) over ()
) as worker,
(sum(case when title = 'manager' then 1 else 0 end) /
sum(sum(case when title = 'manager' then 1 else 0 end)) over ()
) as manager
from ta
group by status;
Here 是一个 sql小提琴。
【讨论】:
以上是关于如何在数据透视语句中包含百分比计算的主要内容,如果未能解决你的问题,请参考以下文章