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。

4

3 回答 3

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')
于 2013-08-26T04:16:20.593 回答
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’)
于 2013-08-26T09:37:25.030 回答
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')
于 2013-08-26T04:17:13.483 回答