How to select overlapping date ranges in SQL

前端 未结 2 491
被撕碎了的回忆
被撕碎了的回忆 2021-01-22 10:44

I have a table with the following columns : sID, start_date and end_date

Some of the values are as follows:

1   1995-07-28  2003-07-20 
1   2003-07-21  2         


        
2条回答
  •  渐次进展
    2021-01-22 11:01

    One way of doing this reasonably efficiently is

    WITH T1
         AS (SELECT *,
                    MAX(end_date) OVER (PARTITION BY sID ORDER BY start_date) AS max_end_date_so_far
             FROM   YourTable),
         T2
         AS (SELECT *,
                    range_start = IIF(start_date <= LAG(max_end_date_so_far) OVER (PARTITION BY sID ORDER BY start_date), 0, 1),
                    next_range_start = IIF(LEAD(start_date) OVER (PARTITION BY sID ORDER BY start_date) <= max_end_date_so_far, 0, 1)
             FROM   T1)
    SELECT SId,
           start_date,
           end_date
    FROM   T2
    WHERE  0 IN ( range_start, next_range_start ); 
    

    if you have an index on (sID, start_date) INCLUDE (end_date) this can perform the work with a single ordered scan.

提交回复
热议问题