2013-12-09 28 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