Last active
December 15, 2021 03:46
-
-
Save FlameWert/9367f63e6c8b25e952a1259c7729507c to your computer and use it in GitHub Desktop.
Merge Overlapping Date Ranges in SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @T table (GroupSourceID varchar(100), EmployeeID VARCHAR(100), StartDate datetime, EndDate datetime); | |
insert into @T values | |
('Green', '1' , '2017-01-02 00:00' , '2017-03-28 00:10'), | |
('Green', '1' , '2017-05-14 23:50' , '2017-05-29 23:50'), | |
('Green', '1' , '2017-04-14 23:50' , '2018-05-29 23:50'), | |
('Yellow', '2' , '2017-05-18 00:00' , '2017-05-18 04:00'), | |
('Yellow', '2' , '2017-05-18 02:00' , '2017-05-18 03:00'), | |
('Yellow', '1' , '2017-05-18 02:00' , '2017-05-18 03:00'), | |
('Blue', '1', '2017-01-02 00:00' , '2017-01-17 15:50'), | |
('Blue', '1', '2017-01-12 00:00' , '2017-02-17 15:50'), | |
('Blue', '3' , '2017-01-14 03:50' , '2017-01-28 15:50'), | |
('Blue', '3' , '2018-01-14 03:50' , '2018-01-28 15:50'); | |
--SELECT * FROM @T; | |
WITH StartDates AS | |
( | |
SELECT DISTINCT GroupSourceID, EmployeeID, StartDate | |
FROM @T AS T1 | |
WHERE NOT EXISTS | |
(SELECT * FROM @T AS T2 | |
WHERE T1.GroupSourceID = T2.GroupSourceID AND T1.EmployeeID = T2.EmployeeID | |
AND T2.StartDate < T1.StartDate | |
AND T2.EndDate >= T1.StartDate) | |
), | |
EndDates AS | |
( | |
SELECT DISTINCT GroupSourceID, EmployeeID, EndDate | |
FROM @T AS T1 | |
WHERE NOT EXISTS | |
(SELECT * FROM @T AS T2 | |
WHERE T1.GroupSourceID = T2.GroupSourceID AND T1.EmployeeID = T2.EmployeeID | |
AND T2.EndDate > T1.EndDate | |
AND T2.StartDate <= T1.EndDate) | |
) | |
SELECT GroupSourceID, EmployeeID, | |
StartDate, | |
(SELECT MIN(EndDate) | |
FROM EndDates AS E | |
WHERE E.GroupSourceID = S.GroupSourceID AND E.EmployeeID = S.EmployeeID | |
AND EndDate >= StartDate) AS EndDate | |
FROM StartDates AS s; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obtained solution from this Stack Overflow question.
https://stackoverflow.com/questions/48425120/merge-overlapping-dates-in-sql-server