我试图在where子句中写一个case语句。以下是我的查询。我想根据工作日执行查询。基本上如果它的星期一它需要是datecreated = getdate() - 3 如果它的星期二它需要是在getdate() - 3和getdate() - 1之间创建的范围日期 如果是星期五那么它需要是datecreated = getdate() - 1
SELECT Count(dispute_reference_no)AS reg_inc
FROM mytable
WHERE reasoncd IN ('b2', 'b3')
AND datecreated = (
CASE
WHEN Datename(weekday,Getdate()) = 'Monday' THEN dbo.Fn_getdateonly(Getdate()-3))
WHEN datename(weekday,getdate()) = 'tuesday' THEN (dbo.fn_getdateonly(getdate()-3)
AND dbo.fn_getdateonly(getdate()))
ELSE dbo.fn_getdateonly(getdate()-1)
END)
以上代码无效。它不会让我在case语句中添加一个范围。
答案 0 :(得分:1)
您无法像这样动态重写where
子句,但您可以通过使用一系列逻辑运算符来获得所需的行为:
SELECT COUNT(Dispute_Reference_no) AS reg_inc
FROM mytable
WHERE reasoncd in ('b2', 'b3') AND
((DATENAME(weekday, GETDATE()) = 'monday' AND
datecreated = dbo.fn_getdateonly(GETDATE()-3)) OR
(DATENAME(weekday, GETDATE()) = 'tuesday' AND
datecreated BETWEEN dbo.fn_getdateonly(GETDATE()-3) AND
dbo.fn_getdateonly(GETDATE())) OR
(atecreated = dbo.fn_getdateonly(GETDATE()-1)
)