I have a mapping table as follows :
FirstEntityID int
MappedTo int
BeginDate Date
EndDate Date
and lets say I have following records in the table :
FirstEntityID MappedTo BeginDate EndDate
1 2 2012-09-01 2012-10-01
2 3 2012-09-01 2012-10-01
1 2 2012-10-02 2012-11-24
2 3 2012-11-01 2012-11-24
I need a script which will get this table and merges records based on the Start and end date to return a result like :
FirstEntityID MappedTo BeginDate EndDate
1 2 2012-09-01 2012-11-24
2 3 2012-09-01 2012-10-01
2 3 2012-11-01 2012-11-24
Using CTEs, we find the starting dates first:
then the ending dates:
and the final result:
Tested in SQL-Fiddle