SELECT trends.[PreviousSales]
, trends.[CurrentSales]
,CASE WHEN trends.[CurrentSales] - trends.[PreviousSales] IS NULL
THEN 0 ELSE trends.[CurrentSales] - trends.[PreviousSales]
END AS [DeltaSales]
基本上DeltaSales = CurrentSales-PreviousSales。如果其中一个值为NULL,则计算显然会失败。
当Sales字段中的任何一个包含null时,如何重新构造CASE语句以替换为0,以便计算正确执行?当前CASE仅在计算失败时才置零。可能是嵌套的CASE?
答案 0 :(得分:3)
使用COALESCE怎么样?
SELECT trends.[PreviousSales]
, trends.[CurrentSales]
, COALESCE(trends.[CurrentSales], 0) - COALESCE(trends.[PreviousSales], 0)