如何按月分组整个日历年,直到本月在SQL中

时间:2014-10-30 01:24:30

标签: sql sql-server sql-server-2008 group-by subquery

我有这个查询

DECLARE @DATE datetime 
SELECT @Date = '2014-04-01' 
SELECT @Date,  COUNT(*) FROM Claim C 
INNER JOIN Prop_Vehicles PV ON PV.Prop = C.Prop
WHERE PV.Vehicle IN (1,2) AND
C.DateCreate >= @DATE AND
ClaimCodeId =5 

我希望按月分组为法定年度。例如

April 2014 - 200
May  2014 - 300
June 2014 - 500
.
.
october 2014 - 100
像这样的事情。怎么实现呢?有人可以帮助我如何将@Date分成两个字段,并按月分组,直到当月如上所述?

我认为datepart函数会怎么做?我也要检查一下。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

如果某些月份没有数据,那么这将会跳过这几个月。

如果你想要所有月数据,即使值为零,那么你需要构建月表并加入它

SELECT DATEADD(MONTH, DATEDIFF(MONTH,0,C.DateCreate), 0), COUNT(*) FROM Claim C 
INNER JOIN Prop_Vehicles PV ON PV.Prop = C.Prop
and PV.Vehicle IN (1,2) AND
and C.DateCreate >= @DATE AND
AND ClaimCodeId =5 
group by DATEADD(MONTH, DATEDIFF(MONTH,0,C.DateCreate), 0)

根据最新评论

这里是获取所有月份数据以及显示年份和月份的方法

DECLARE @DATE datetime 
SELECT @Date = '2014-04-01'

;with cte
as
(
select DATEADD(month, datediff(month,0,@Date), 0) as monthVal,1 as N
union all
select DATEADD(month, datediff(month,0,@Date)+N, 0) as monthVal, N+1
FROM cte
WHERE n <=5
)
SELECT DATENAME(year, monthval) as Year, datename(month,monthVal) as Month, COUNT(*) FROM 
cte
left join Claim C
on DATEADD(month, datediff(month,0,C.DAteCreate)= cte.monthVal
INNER JOIN Prop_Vehicles PV ON PV.Prop = C.Prop
and PV.Vehicle IN (1,2) AND
and C.DateCreate >= @DATE AND
AND ClaimCodeId =5 
group by DATENAME(year, monthval) , datename(month,monthVal)