-2

I have a table with appointments each having start_time and end_time. Is there an efficient way to find overlapping appointments using SQL Server?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1480192
  • 665
  • 8
  • 23

2 Answers2

1

Here is one method to find any appointment that overlaps with the next appointment:

select a.*
from (select a.*, lead(start_time) over (order by start_time, id) as next_start_time
      from appointments a
     ) a
where next_start_time < end_time;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

It is a simple join:

DECLARE @t TABLE ( ID INT, ST TIME, ET TIME )

INSERT  INTO @t
VALUES  ( 1, '8:00', '9:00' ),
        ( 2, '9:00', '10:00' ),
        ( 3, '12:00', '13:00' ),
        ( 4, '12:30', '13:30' ),
        ( 5, '13:10', '13:20' ),
        ( 6, '14:00', '15:00' )


SELECT  t1.ID, t2.ID
FROM    @t t1
        JOIN @t t2 ON t1.ID < t2.ID 
                      AND (t1.ST > t2.ST
                      AND t1.ST < t2.ET
                      OR  t1.ET > t2.ST
                      AND t1.ET < t2.ET)

Output:

ID1 ID2
3   4
4   5

The idea here is to find lines when at least one edge of line is between the edges of other line:

   a--------------------b
c-------------d


   a--------------------b
              c-------------d


   a--------------------b
         c--------d

If [cd] overlaps [ab] at least c or d will be between a and b.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
  • What when [cd] is larger than [ab] meaning c is before a and d is after b? – user1480192 Mar 09 '15 at 10:24
  • @user1480192, since it is a join on itself it will check both situations. That's why there is checking for duplicates. Imagine that you have [x1, x2] and [y1, y2] intervals in your table. Self join will check both sides: it will assign x1 to a, x2 to b, y1 to c, y2 to d. Then it will assign x1 to c, x2 to d, y1 to a y2 to b. – Giorgi Nakeuri Mar 09 '15 at 10:30