这是我的查询
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
我的查询中存在某种问题,这就是为什么它会在同一个月返回多个数据,如
请帮我解决问题。感谢
答案 0 :(得分:0)
我建议使用Month()
函数返回每个月的数值,而不是使用CurDate
作为年,月,日的完整日期。这将允许您按月分组而不是完整日期:
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;