使用 CASE 语句时查询未返回预期结果

Query is not returning expected results when using CASE statement

SELECT
    b.Part,
    b.PartCreated,
    b.LastSalesDate,
    CASE WHEN b.LastSalesDate < (getdate()-365) OR b.LastSalesDate IS NULL AND b.PartCreated <= '2013-12-31' THEN 'C'
         WHEN b.LastSalesDate < (getdate()-365) OR b.LastSalesDate IS NULL AND b.PartCreated >= '2014-01-01' THEN 'N'
    ELSE 'D'
    END AS PartType

我在 运行 此查询时得到不正确的结果。一些 PartType 值在应该是 'N' 时变成了 'C'。例如,部件 123456 的 PartCreated 值为 02-17-2014,LastSalesDate 值为 08-01-2014,PartType 值应为 'N',但查询返回 'C'。我该如何修复查询?

ANDOR 具有更高的优先级,因此 case 表达式的计算可能不是您所期望的。

你的条件被评估为a or (b and c)但你想要(a or b) and c

您可以通过添加括号来更改评估:

CASE WHEN (b.LastSalesDate < (getdate()-365) OR b.LastSalesDate IS NULL) AND b.PartCreated <= '2013-12-31' THEN 'C'
     WHEN (b.LastSalesDate < (getdate()-365) OR b.LastSalesDate IS NULL) AND b.PartCreated >= '2014-01-01' THEN 'N'
ELSE 'D'
END AS PartType