Merge overlapping date intervals

后端 未结 7 995
不知归路
不知归路 2020-11-27 16:16

Is there a better way of merging overlapping date intervals?
The solution I came up with is so simple that now I wonder if someone else has a better idea of how this cou

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 16:44

    I was looking for the same solution and came across this post on Combine overlapping datetime to return single overlapping range record.

    There is another thread on Packing Date Intervals.

    I tested this with various date ranges, including the ones listed here, and it works correctly every time.


    SELECT 
           s1.StartDate,
           --t1.EndDate 
           MIN(t1.EndDate) AS EndDate
    FROM @T s1 
    INNER JOIN @T t1 ON s1.StartDate <= t1.EndDate
      AND NOT EXISTS(SELECT * FROM @T t2 
                     WHERE t1.EndDate >= t2.StartDate AND t1.EndDate < t2.EndDate) 
    WHERE NOT EXISTS(SELECT * FROM @T s2 
                     WHERE s1.StartDate > s2.StartDate AND s1.StartDate <= s2.EndDate) 
    GROUP BY s1.StartDate 
    ORDER BY s1.StartDate 
    

    The result is:

    StartDate  | EndDate
    2010-01-01 | 2010-06-13
    2010-06-15 | 2010-06-25
    2010-06-26 | 2010-08-16
    2010-11-01 | 2010-12-31
    

提交回复
热议问题