根据列值更改where子句条件

时间:2012-08-07 19:57:48

标签: sql case where

我试图弄清楚如何在where子句中使用case语句,以便根据Product type列选择特定条件。 where子句的第一部分对两个场景都是通用的。如果产品类型是STD,我需要检查EntryDate是否在当月和昨天的第一天之间。如果产品是LTD,那么我需要检查EntryDate是否在昨天和七天之前。

DECLARE @firstDayOfCurrentMonth datetime
SET @firstDayOfCurrentMonth = CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '/' +  CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '/01' AS DATETIME)

SELECT DCMNumber, COUNT(*) AS PriorDenied
FROM  cauAssignedClaim 
WHERE RecordType = 'A' AND [Status] IS NULL AND
CASE WHEN Product = 'LTD' THEN EntryDate BETWEEN @firstDayOfCurrentMonth AND GETDATE()-1 
CASE WHEN Product = 'STD' THEN  EntryDate BETWEEN DATEADD(Day, -7, GETDATE()-1) AND GETDATE()-1 
END
GROUP BY [Status],  DCMNumber

2 个答案:

答案 0 :(得分:2)

此处无需使用CASE声明。您可以在WHERE上添加其他条款:

DECLARE @firstDayOfCurrentMonth datetime
SET @firstDayOfCurrentMonth = CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '/' +  CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '/01' AS DATETIME)

SELECT DCMNumber, COUNT(*) AS PriorDenied
FROM  cauAssignedClaim 
WHERE RecordType = 'A' 
    AND [Status] IS NULL 
    AND 
    ( 
        (
            Product = 'LTD' 
            AND EntryDate BETWEEN @firstDayOfCurrentMonth AND GETDATE()-1 
        )
        OR
        (
            Product = 'STD'
            AND EntryDate BETWEEN DATEADD(Day, -7, GETDATE()-1) AND GETDATE()-1 
        )
    )

GROUP BY [Status],  DCMNumber

就像仅供参考,这是获得本月第一天的较短方式:

SELECT DATEADD(m,DATEDIFF(m,0,getdate()),0)

答案 1 :(得分:0)

你想要

WHERE EntryDate BETWEEN 
  CASE WHEN Product = 'LTD' THEN @FirstDatetc 
       ELSE DateAdd(blah)
  END 
AND GetDate()-1

假设这是有效的语法,因为我从未尝试过它:)

我更喜欢这个,因为它非常简洁 - 如果你格式化它我觉得它也很可读