tags:

views:

1160

answers:

2

i have two tables, both with start time and end time fields. i need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect

for example:

           <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->

please phrase your answer in the form of a SQL where-clause, AND consider the case where the end time in the second table may be NULL

target platform is sql server 2005, but solutions from other platforms may be of interest also

+13  A: 
SELECT * 
FROM table1,table2 
WHERE table2.start <= table1.end 
AND (table2.end IS NULL OR table2.end >= table1.start)
Khoth
+1  A: 
select * from table_1 
right join 
table_2 on 
(
table_1.start between table_2.start and table_2.[end]
or
table_1.[end] between table_2.start and table_2.[end]
or
(table_1.[end] > table_2.start and table_2.[end] is null)
)

EDIT: Ok, don't go for my solution, it perfoms like shit. The "where" solution is 14x faster. Oops...

Some statistics: running on a db with ~ 65000 records for both table 1 and 2 (no indexing), having intervals of 2 days between start and end for each row, running for 2 minutes in SQLSMSE (don't have the patience to wait)

Using join: 8356 rows in 2 minutes

Using where: 115436 rows in 2 minutes

Casper
i think you mean table_1.[start] >= table_2.start ... in the last clause?
Steven A. Lowe
Depends on your needs. I considered a row in table 2 that started between table 1's start and end as within the range as well.
Casper
@[Casper] my mistake, i misread the intent of that clause, sorry!
Steven A. Lowe