0

我是使用带有 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

电流输出:

在此处输入图像描述

想要的输出... 在此处输入图像描述

4

1 回答 1

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
于 2013-05-13T20:51:41.260 回答