2013-05-13 92 views
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 

電流輸出:

enter image description here

所需的輸出... enter image description here

+0

坦率地說,我會看到最後一位作爲前端(也許Excel作爲你的例證建議)工作 – 2013-05-13 20:24:32

回答

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 
+0

戈登上述作品腳本謝謝。如果我想要十進制格式的結果,我該如何轉換。 – Tone 2013-05-14 15:31:55

+0

@聲調。 。 。有幾種方法。一種是轉換爲諸如「decimal(10,2)」之類的格式。 – 2013-05-15 13:20:35