Tuesday, February 26, 2013

SQL Query to Find Overlapping (Conflicting) Date Ranges


-- 2.1) select date ranges that lie outside [d1, d2] (d2 and end_date are inclusive)
SELECT * FROM <table> WHERE @d2 <  start_date OR  end_date <  @d1

-- 2.2) select date ranges that overlap [d1, d2] (d2 and end_date are inclusive)
SELECT * FROM <table> WHERE @d2 >= start_date AND end_date >= @d1
The above queries are based on Allen's Interval Algebra. The following ASCII art should explain the first query:
       @d1 |--------| @d2       
           .        . |--------| @d2 < start_date
           .        |--------|   @d2 = start_date
|--------| .        .            end_date < @d1
  |--------|        .            end_date = @d1
    |--------|      .            
           .      |--------|     
           |--------|            
           . |----| .            
         |------------|          

Link for more detail input.

No comments:

Post a Comment