【问题标题】:SQL Server - check if sets of time ranges overlap each otherSQL Server - 检查时间范围集是否相互重叠
【发布时间】:2017-05-23 15:03:30
【问题描述】:

我有两张表,其中包含时间范围、周和期间: 周数:

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 表。换句话说,我需要从周中删除 StartDate 和 EndDate 之间的时间与周期表中的任何时间段没有任何共同的日期。任何想法如何做到这一点?

结果周表应该是:

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

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

【问题讨论】:

  • 你的 dbms 是什么?
  • 我不知道,我只是用'@Weeks'和'@Periods'表写一个SP。
  • 您使用的是什么数据库? Oracle、SQL Server、MySQL、Postrgres 等?
  • 我正在使用 SQL Server

标签: sql sql-server date overlap


【解决方案1】:

这将返回不与Period 重叠的Weeks

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

要仅选择与Periods 重叠的Weeks,请将not exists() 更改为exists()

【讨论】:

  • 谢谢。我试试这个。
猜你喜欢
  • 1970-01-01
  • 2016-06-30
  • 2021-12-27
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多