简体   繁体   中英

How to group by month and year for entire calender year until this month in SQL

I have this query

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 

I want to group by month wise for the calnder year. For example

April 2014 - 200
May  2014 - 300
June 2014 - 500
.
.
october 2014 - 100

something like this. How to achieve it? Could someone help me how to split @Date into two fields and also group by month year wise until current month like I mentioned above?

I reckon datepart function would do? Let me also check that.

Thank you in advance.

In case some months don't have data then this would skip those months.

If you want all months data even if value is zero, then you need to construct months table and join with it

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)

as per latest comment

here is the way to get all months data and also to display year and month

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM