CREATE
TABLE
Enrollments (
StudentId
INT
NOT
NULL
,Enroll_Date
DATE
,Class
VARCHAR
(30)
)
ALTER
Enrollments
ADD
CONSTRAINT
PK_Enrollments_StudentID_Enroll_Date
PRIMARY
KEY
(
INSERT
INTO
VALUES
1001
,
'20130101'
'Dance'
,(
'20130401'
'Swimming'
'20130601'
'Karate'
IF OBJECT_ID(
'tempdb..#Tally'
, N
'U'
IS
DROP
#Tally;
SELECT
TOP
2000000 IDENTITY(
, 1, 1)
AS
N
#Tally
FROM
Master.dbo.SysColumns sc1
,Master.dbo.SysColumns sc2
UNIQUE
CLUSTERED
INDEX
cx_Tally_N
ON
#Tally (N);
CAST
(dateadd(
month
, N-1,
'19000101'
the_date
dbo.Calendar
#Tally T
WHERE
N <= datediff(
'20200101'
);
;
WITH
cte
S.StudentId
,S.Enroll_Date
Start_Date
COALESCE
(DATEADD(
, - 1, N.Enroll_Date), DATEADD(
, DATEDIFF(
CURRENT_TIMESTAMP
),
))
End_Date
,S.Class
Enrollments S
OUTER
APPLY (
(1) Enroll_Date
Enrollments E
E.StudentId = S.StudentId
AND
E.Enroll_Date > S.Enroll_Date
ORDER
BY
Enroll_Date
) N)
*
cte;
S.StudentId, Cal.the_date
Enroll_Date, S.Class
cte S
INNER
JOIN
dbo.Calendar Cal
Cal.the_date
BETWEEN
S.Start_Date
S.End_Date;
;WITH
,DATEADD(
, -1,LEAD(S.Enroll_Date, 1, DATEADD(
day
, 1, EOMONTH(
))) OVER (PARTITION
S.Enroll_Date))
This article participated in the TechNet Guru for August competition and won the Silver Medal.
Naomi N edited Revision 16. Comment: Addendum section
This article has been featured in the weekly Top Contributors awards - blogs.technet.com/.../top-contributors-meet-maheshkumar-read-about-windows-server-2012-t-sql-guru-entries-data-protection-manager-and-real-life-ninjas-d.aspx