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'。例如,Part 123456的PartCreated值为02-17-2014,LastSalesDate值为08-01-2014,PartType值应为'N',但查询返回'C'。我该如何修复查询?
答案 0 :(得分:1)
AND
的优先级高于OR
,因此对案例表达式的评估可能与您的预期不同。
您的情况评估为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