使用BETWEEN日期

时间:2016-08-08 09:42:34

标签: sql-server-2014 ssms-2014

语法有问题,需要根据数字和日期范围返回结果,如果是6,2那么这个日期范围就是其他日期范围。

DECLARE @Test TABLE 

(
ID NVARCHAR(10)
,Number INT
,[Date] DATETIME

)
INSERT INTO @Test VALUES ('TG32',6,'20160715')
INSERT INTO @Test VALUES ('TG47',6,'20160803')
INSERT INTO @Test VALUES ('AG9',6,'20160805')
INSERT INTO @Test VALUES ('BF27',2,'20160804')
INSERT INTO @Test VALUES ('QD65',2,'20160802')
INSERT INTO @Test VALUES ('F98',0,'20160806')
INSERT INTO @Test VALUES ('GC5',0,'20160731')
INSERT INTO @Test VALUES ('HT76',0,'20160802')
INSERT INTO @Test VALUES ('KL81',0,'20160805')
INSERT INTO @Test VALUES ('WR52',0,'20160802');

SELECT TOP 10 * FROM @Test

WHERE [Date] = CASE WHEN Number IN ('6','2') THEN  ([Date] BETWEEN CAST(GETDATE() - 6 AS date) AND GETDATE()) 
ELSE ([Date] BETWEEN CAST(GETDATE() - 1 AS date) AND GETDATE()) END 

2 个答案:

答案 0 :(得分:0)

你不能以这种方式使用CASE,在sql情况下不像if then else它更类似于函数(test?if_yes; if_not)

WHERE [Date] BETWEEN CAST(GETDATE() - CASE WHEN Number IN ('6','2') THEN 6 ELSE 0 END AS date) AND GETDATE() 

答案 1 :(得分:0)

where子句中的CASE应返回一个值,而不是多个值..

尝试以下所有的联盟..

SELECT TOP 10 * FROM @Test
WHERE number in (6,2) and  [Date]BETWEEN CAST(GETDATE() - 6 AS date) AND GETDATE()
union all
SELECT TOP 10 * FROM @Test
WHERE number not in (6,2) and  [Date] BETWEEN CAST(GETDATE() -  1 as date) AND GETDATE()