1

语法有问题,需要根据数字和日期范围返回结果,如果它是 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 
4

2 回答 2

0

你不能这样使用CASE,在sql case 中不像if then else它更类似于function (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() 
于 2016-08-08T09:47:09.190 回答
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()
于 2016-08-08T10:40:01.503 回答