SQL Server - 检查时间范围集是否相互重叠

时间:2017-05-23 15:03:31

标签: sql sql-server date overlap

我有两张时间范围表,周和期间: 周:

WeekID | StartDate  | EndDate    |
1      | 2017-01-01 | 2017-01-07 |
2      | 2017-01-08 | 2017-01-14 |
3      | 2017-01-15 | 2017-01-21 |

和期间:

PeriodID | StartDate  | EndDate    |
1        | 2016-12-01 | 2017-01-03 |
2        | 2017-01-20 | 2017-02-28 |
3        | 2017-03-15 | 2017-03-16 |

我需要只有表Weeks中的那些记录,这些记录有一些日期范围来自Periods表的常见日期。换句话说,我需要从Weeks中删除,其中StartDate和EndDate之间的时间与句点表中的任何时间段没有任何共同日期。有什么想法怎么做?

结果Weeks表应为:

WeekID | StartDate  | EndDate    |
1      | 2017-01-01 | 2017-01-07 |
3      | 2017-01-15 | 2017-01-21 |

对此的任何想法都会有所帮助。

1 个答案:

答案 0 :(得分:1)

这将返回与Weeks不重叠的Period

select *
from Weeks w
where not exists (
    select 1
    from Weeks l
      inner join Periods r
        on l.EndDate >= r.StartDate
       and r.EndDate >= l.StartDate
    where w.WeekId = l.WeekId 
  )

rextester演示:http://rextester.com/VYTEC19325

返回:

+--------+------------+------------+
| WeekId | StartDate  |  EndDate   |
+--------+------------+------------+
|      2 | 2017-01-08 | 2017-01-14 |
+--------+------------+------------+

要删除Weeks,请将select *更改为delete

只需选择Weeks重叠Periods not exists()更改为exists()