2013-12-09 31 views
0

這是我的查詢透視表日期及年份明智的數據顯示SQL Server 2005中

SELECT * 
FROM (SELECT CurDate, YEAR(CurDate) AS orderyear, Warranty_Info 
     FROM eod_main where year(CurDate)>=2009 and year(CurDate)<=2011) AS D 
    PIVOT(SUM(Warranty_Info) FOR orderyear IN([2009],[2010],[2011])) AS P 

上面的查詢返回的數據,但它是CURDATE歸期是返回多個日期爲當月。

我想,SUM(Warranty_Info)應每月和每年返回一次

輸出應該像

Month  2009  2010 2011 2012 2013 
-----  ----  ---- ---- ---- ----- 
1   10  0  11  32  98 
2   20  10  21  11  44 
3   0  224  33  77  31 

某種問題是有我的查詢,這就是爲什麼它返回多個數據對於同一個月像

enter image description here

請幫我有權查詢。謝謝

回答

0

而不是使用CurDate作爲全年日,年,月和日,我建議使用Month()函數返回每月的數值。這將允許您按月份而不是完整的日期:

SELECT dateMonth, [2009],[2010],[2011] 
FROM 
(
    SELECT month(CurDate) dateMonth, 
    YEAR(CurDate) AS orderyear, Warranty_Info 
    FROM eod_main 
    where year(CurDate)>=2009 
    and year(CurDate)<=2011 
) AS D 
PIVOT 
(
    SUM(Warranty_Info) 
    FOR orderyear IN([2009],[2010],[2011]) 
) AS P; 

SQL Fiddle with Demo