2011-02-15 48 views
0

我們有例如。以下表格如何在SQL Server中確定dateTime範圍是否與另一個範圍重疊

| ID | startDateTime  | endDateTime   | 
+----+---------------------+---------------------| 
| 1 | 2010-01-01 10:30:00 | 2010-01-01 11:00:00 | 
| 2 | 2010-01-01 10:30:00 | 2010-01-01 11:30:00 | 
| 3 | 2010-01-01 11:00:00 | 2010-01-01 11:30:00 | 
| 4 | 2010-01-01 11:00:00 | 2010-01-01 12:00:00 | 
| 5 | 2010-01-01 11:30:00 | 2010-01-01 12:00:00 | 
| 6 | 2010-01-01 10:30:00 | 2010-01-01 12:00:00 | 

我會例如。針對與

@startDateTime 2010-01-01 11:00:00 
@endDateTime 2010-01-01 11:30:00 

我要查詢來獲取以下ID:2,3,4,6

我的大腦是辦法古怪產生正確的說法... :(

回答

3

你可以這樣做

declare @T table (ID int, startDateTime datetime, endDateTime datetime) 

insert into @T values 
( 1 , '2010-01-01 10:30:00' , '2010-01-01 11:00:00'), 
( 2 , '2010-01-01 10:30:00' , '2010-01-01 11:30:00'), 
( 3 , '2010-01-01 11:00:00' , '2010-01-01 11:30:00'), 
( 4 , '2010-01-01 11:00:00' , '2010-01-01 12:00:00'), 
( 5 , '2010-01-01 11:30:00' , '2010-01-01 12:00:00') 

declare @startDateTime datetime 
declare @endDateTime datetime 


set @startDateTime = '2010-01-01 11:00:00' 
set @endDateTime = '2010-01-01 11:30:00' 

select * 
from @T 
where 
    startDateTime < @endDateTime and 
    endDateTime > @startDateTime 
+0

+1可能要使用> =和<=,這取決於您的'重疊'的條件 – sasfrog 2011-02-15 10:55:30

相關問題