将“X row”列的百分比添加到SQL pivot

时间:2018-06-14 09:25:50

标签: sql sql-server tsql pivot

我已经创建了一个SQL数据透视图,并希望根据其中的聚合数字添加进一步计算的百分比列,我无法弄清楚如何实现这一点。

以下是代码:

Select * from (

Select  
        c_group2 as [Group],
        year(period) as [Year],
        transvalue as [Total],
        from transactions) as s

PIVOT

(       Sum(Total)
        for [Year] in ([2018],[2017],[2016],[2015])) as pvt

这会产生以下输出:

Group | 2018 | 2017 | 2016 | 2015

Sales | 30000| 28000| 25000| 21000

Exp1  | 5000 | 3100 | 3000 | 2500

Exp2  | 600  | 700  | 1000 | 500 

我想要包含的其他列将计算每个费用行(Exp1,Exp2)占该年度销售总额的百分比,给出以下输出:

Group | 2018 | %   | 2017 | %   | 2016 | %   | 2015 | %

Sales | 30000|     | 28000|     | 25000|     | 21000|

Exp1  | 5000 | 16.6| 3100 | 11.0| 3000 | 12.0| 2500 | 11.9

Exp2  | 600  |  2.0| 700  |  2.5| 1000 |  4.0| 500  |  2.3

每年都有效,它是Exp1 / Sales,然后是Exp2 / Sales等等,可能是初始子查询中的计算。

1 个答案:

答案 0 :(得分:2)

如果销售额不是透视列中的最大金额,那么您可以使用下面的内部查询

Select [Group],
 [2018],[2018%]=CASE WHEN Group<>'Sales' THEN 100.00* [2018]/ SUM(CASE WHEN Group='Sales' THEN [2018] END) OVER() END,
 [2017],[2017%]=CASE WHEN Group<>'Sales' THEN 100.00* [2017]/ SUM(CASE WHEN Group='Sales' THEN [2017] END) OVER() END,
 [2016],[2016%]=CASE WHEN Group<>'Sales' THEN 100.00* [2016]/ SUM(CASE WHEN Group='Sales' THEN [2016] END) OVER() END,
 [2015],[2015%]=CASE WHEN Group<>'Sales' THEN 100.00* [2015]/ SUM(CASE WHEN Group='Sales' THEN [2015] END) OVER() END
from (

Select  
        c_group2 as [Group],
        year(period) as [Year],
        transvalue as [Total],
        from transactions) as s

PIVOT

(       Sum(Total)
        for [Year] in ([2018],[2017],[2016],[2015])) as pvt