0

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

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
4

2 回答 2

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)
于 2012-08-07T20:02:33.513 回答
0

你要

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

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

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

于 2012-08-07T20:02:45.297 回答