我是新手使用带有sql的数据透视表,并且一直坚持这个特殊问题,我希望有人可以提供帮助。我的脚本返回一个作业列表,并计算每年的作业。我想添加一个与上一年相比增加或减少百分比的列。
SELECT *
FROM
(
SELECT [year_time], [assignment_code], [assignment_desc]
FROM raw_teacher
) AS source
PIVOT
(
COUNT(assignment_code)
FOR [year_time] IN ([2012], [2011], [2010], [2009], [2008])
) as pvt
当前输出:
期望的输出......
答案 0 :(得分:1)
您可以直接进行计算:
with cte as (
SELECT *
FROM
(
SELECT [year_time], [assignment_code], [assignment_desc]
FROM raw_teacher
) AS source
PIVOT
(
COUNT(assignment_code)
FOR [year_time] IN ([2012], [2011], [2010], [2009], [2008])
) as pvt
)
select assignment_desc, [2012], [2012]/[2011], [2011], [2011]/[2010],
[2010], [2010]/[2009], [2009], [2009]/[2008], [2008]
from cte
如果值可以为0,那么您需要检查:
select asignment_desc,
[2012], (case when [2011] <> 0 then [2012]/[2011] end),
[2011], (case when [2010] <> 0 then [2011]/[2010] end),
. . .
from cte