2013-08-26 142 views
2

看起來應該有一種方法可以使其更高效。難度是任意的日期範圍和所述範圍的數量。根據多個日期範圍優化查詢選擇

在此查詢中,我試圖從任務表中檢索行,其中日期(無論何時)是2013-01-01,2013-01-03,2013-01-09或2013-02-01

tasks 

|id  | int  | 
|begin_date| datetime | 

SELECT * FROM tasks 
WHERE (tasks.begin_date >= '2013-01-01' AND tasks.begin_date < '2013-01-01') 
OR (tasks.begin_date >= '2013-01-03' AND tasks.begin_date < '2013-01-04') 
OR (tasks.begin_date >= '2013-01-09' AND tasks.begin_date < '2013-01-10') 
OR (tasks.begin_date >= '2013-02-01' AND tasks.begin_date < '2013-02-02') 

有沒有一個「適當」的方式來做到這一點?還是更有效率的方式?

我使用SQL Server 2008的

+0

下面兩個答案(一個部分似乎從另一個複製!)已複製的使用「2013-01-01」你的錯誤,而不是「2013 -01-02' –

回答

3

請試試這個

select * from tasks 
where Convert(varchar,begin_date,103) in 
('01/01/2013','04/01/2013','10/01/2013','02/02/2013') 

,或者你也可以試試這個。

select * from tasks 
where (Convert(varchar,begin_date,103) ='01/01/2013' 
OR Convert(varchar,begin_date,103) = '04/01/2013' 
OR Convert(varchar,begin_date,103) = '10/01/2013' 
OR Convert(varchar,begin_date,103) = '02/02/2013') 

或第三種方法,

SELECT * FROM tasks 
WHERE (tasks.begin_date BETWEEN '2013-01-01' AND '2013-01-01') 
OR (tasks.begin_date BETWEEN '2013-01-03' AND '2013-01-04') 
OR (tasks.begin_date BETWEEN '2013-01-09' AND '2013-01-10') 
OR (tasks.begin_date BETWEEN '2013-02-01' AND '2013-02-02') 
1

使用此,

SELECT * FROM tasks 
WHERE (tasks.begin_date BETWEEN '2013-01-01' AND '2013-01-01') 
OR (tasks.begin_date BETWEEN '2013-01-03' AND '2013-01-04') 
OR (tasks.begin_date BETWEEN '2013-01-09' AND '2013-01-10') 
OR (tasks.begin_date BETWEEN '2013-02-01' AND '2013-02-02') 
+0

之間是包容性的,所以不會從'2013-02-01'和任何'2013-02-02 00:00:00'任何時間捕獲任何任務? –

2

這裏是另外一個。

SELECT * FROM tasks 
WHERE YEAR(tasks.begin_date) = 2013 
and 
(
    (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 1) -- 2013-01-01 
    or 
    (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 3) -- 2013-01-03 
    or 
    (MONTH(tasks.begin_date) = 1 and DAY(tasks.begin_date) = 9) -- 2013-01-09 
    or 
    (MONTH(tasks.begin_date) = 2 and DAY(tasks.begin_date) = 1) -- 2013-02-01 
) 

您也可以嘗試用類似

Convert(DateTime, DATEDIFF(DAY, 0, tasks.begin_date)) = 
Convert(DateTime, ‘01/01/2013’)