根据多个日期范围优化查询选择

时间:2013-08-26 04:09:42

标签: sql sql-server sql-server-2008

似乎应该有一种方法可以提高效率。难点是任意日期范围和所述范围的数量。

在这个查询中,我试图从任务表中检索日期(不论时间)是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。

3 个答案:

答案 0 :(得分: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 :(得分: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’)

答案 2 :(得分: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')