I have a table with the following structure:
StartDate datetime NOT NULL
EndDate datetime NOT NULL
EnrollmentId nvarchar(255) NOT NULL
ProgrammeId nvarchar(255) not null
EnrollmentId
is the primary key, and is a bit like a GUID string, and ProgrammeId
refers to a 'subject code' a bit like a GUID too.
What I want to do is determine the total number of months a Programme
has accrued during a specific date range for ALL enrollments e.g. from 01/01/2011 to 1st April 2014.
So let's say I have an enrollment which exists between 08/08/2010
to 01/01/2012
for a particular programmeId
. I would want to count all the months that had accrued after 01/01/2011
. So any months prior to this date should not count i.e. 08/08/2010 to 31/12/2010 should not be counted.
Ideally I'd like a count of how many months per ProgrammeId
for a given date range.
Just a few notes:
- I would need to count whole months so if an enrollment begins at 08/01/2011 and ends at 20/01/2012 only 12 months should be considered.
- The period in which I want to count the months usually are at the beginning of the respective month i.e. 1st of jan 2011 to 1st of Apr 2014, 1st of May 2014 etc etc.
Some code to return all months for an enrollment:
;with MonthList as (
select
DATEADD(month, M, '12/1/1899') as 'FirstDay',
dateadd(day, -1, dateadd(month, M + 1, '12/1/1899')) as 'LastDay',
DATEADD(month, M + 1, '12/1/1899') as 'FirstDayNextMonth'
from (
select top 3000 ROW_NUMBER() over (order by s.name) as 'M'
from master..spt_values s) s
)
select
t.ProgrammeId, ml.FirstDay, ml.LastDay
from
Enrollment t
inner join MonthList ml
on t.startdate < ml.FirstDayNextMonth
and t.enddate >= ml.FirstDay
Thanks in advance