如何在SQL查询中找到时隙冲突

时间:2014-01-10 14:53:22

标签: sql sql-server sql-server-2008 between

我想找时间冲突,但它没有给我正确的结果以下记录。 我想为时间段返回冲突true - “t1.starttime to t2.endtime”因为此时隙与“t2.starttime和t2.endtime”冲突,因为7到12时间覆盖了8到11.30的某个时间。

t1.StartTime     t1.EndTime       t2.StartTime     t2.EndTime
---------------- ---------------- ---------------- ----------------
07:00:00.0000000 12:00:00.0000000 08:00:00.0000000 11:30:00.0000000

我执行以下查询,但它没有给我结果。

SELECT 
  count(1) 
FROM 
  t1 INNER JOIN t2 ON

  CAST(t1.StartTime as TIME)  
  BETWEEN CAST(t2.StartTime as TIME) 
  AND CAST(t2.EndTime as TIME) OR CAST(t1.EndTime as TIME)  
  BETWEEN CAST(t2.StartTime as TIME) 
  AND CAST(t2.EndTime as TIME)

1 个答案:

答案 0 :(得分:7)

重叠的正确逻辑有点简单:

SELECT count(1) 
FROM t1 INNER JOIN
     t2
     ON CAST(t1.StartTime as TIME) < CAST(t2.EndTime as TIME) and
        CAST(t1.EndTime as TIME) > CAST(t2.StartTime as TIME);

逻辑是一个间隔在另一个间隔开始之前开始,在另一个间隔开始之后结束。