如何在计算中处理1或2 NULL

时间:2018-10-19 18:08:27

标签: tsql case

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?

1 个答案:

答案 0 :(得分:3)

使用COALESCE怎么样?

SELECT trends.[PreviousSales]
       , trends.[CurrentSales]
       , COALESCE(trends.[CurrentSales], 0) - COALESCE(trends.[PreviousSales], 0)