[FIXED] SQL Server - grouping overlapping dates

Issue

I currently have a table that looks like so:

class="s-table">
ID Start_Date End_Date
1 2021-01-10 2021-01-11
1 2021-01-12 2021-01-13
1 2021-04-14 2021-04-15
1 2021-10-01 2021-10-02
1 2021-10-03 2021-10-04
1 2021-10-05 2021-10-06

I need to transform so that any dates that overlap are grouped together like so:

ID Start_Date End_Date
1 2021-01-10 2021-01-13
1 2021-04-14 2021-04-15
1 2021-10-01 2021-10-06

Any help at all would be greatly appreciated.


Solution

That is what you need

WITH cte AS (
    SELECT 
        *,
        SUM(CASE WHEN start_date = DATEADD(day, 1, prev_end_date) THEN 0 ELSE 1 END) OVER (PARTITION BY id ORDER BY rn) AS group_id
    FROM (        
        SELECT 
            *,
            LAG(end_date) OVER (PARTITION BY id ORDER BY start_date) AS prev_end_date,
            ROW_NUMBER() OVER (PARTITION BY id ORDER BY start_date) AS rn
        FROM data        
    ) groups
)
SELECT 
    id,
    MIN(start_date) AS start_date,
    MAX(end_date) AS end_date
FROM cte
GROUP BY id, group_id

You can check a working demo here



Answered By - Alexey
Answer Checked By - Marie Seifert (sql.easybugfix Admin)

Related Posts

Post a Comment