SQL Server query get count of X on 15th of each month -


i create sql query gets count of employees employed of 15th of each month of last 5 years.

this query gets me single month:

select     sum(x.countofemployees) (select     count(cncemployeeid) countofemployees dbo.cncemployees group cncemployeestartdate,          cncemployeedateleft having (cncemployeestartdate < convert(datetime, '2016-07-15 00:00:00', 102)) , ((cncemployeedateleft > convert(datetime, '2016-07-15 00:00:00', 102)) or (cncemployeedateleft null))) x 

what looking output:

jan 2016 - 32 feb 2016 - 33 mar 2016 - 33 

etc. each month have data.

i know how create query , @ least make quick change dates hand adding variable , changing on , on (in fact report done today last 12 months). believe there better way in 1 step without need manually go through each month.

one method generates 60 months , use in join:

with dates (       select cast(dateadd(day, 16 - day(getdate()), getdate()) date) thedate, 1 num       union       select dateadd(month, -1, thedate), num + 1       dates       num <= 60      ) select d.thedate, count(e.cncemployeestartdate) dates d left join      dbo.cncemployees e      on e.cncemployeestartdate <= d.thedate ,         (e.cncemployeedateleft >= d.thedate or e.cncemployeedateleft null) group d.thedate; 

this not efficient method, if have few hundred or thousand employees should fine in terms of performance.


Comments