CASE WHEN NULL查询

时间:2015-07-01 07:17:46

标签: sql-server null case

我有以下现有查询:

SELECT SUM([Sales Amount (Actual)]) * 1.21
  FROM [DATABASE] 
  WHERE [Posting Date] = '2014-06-22' 
  AND [Location Code] = '129'

有时结果是NULL,所以我想编辑查询和结果' 0' 0如果结果为NULL,则显示正常结果。

我已经发现我应该使用CASE和ISNULL或者是NULL,但是我无法让它工作。

SELECT CASE WHEN SUM([Sales Amount (Actual)]) * 1.21
    IS NULL '0' 
    ELSE SUM([Sales Amount (Actual)]) * 1.21
    END FROM [DATABASE] 
    WHERE [Posting Date] = '2015-07-01' AND [Location Code] = '121'  

我收到错误:

  

' 0'

附近的语法不正确

有人可以帮助我吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

SELECT ISNULL(SUM([Sales Amount (Actual)]) * 1.21, 0) Result
  FROM [TABLE] 
  WHERE condition

答案 1 :(得分:1)

你的语法错误。我希望您使用COALESCE(ANSI标准)而不是ISNULL

SELECT COALESCE(SUM([Sales Amount (Actual)]) * 1.21, 0) 
FROM [Table] 
WHERE [Posting Date] = '2015-07-01' AND [Location Code] = '121'  

答案 2 :(得分:0)

<强>问题:

在条件之后使用THEN

SELECT CASE WHEN SUM([Sales Amount (Actual)]) * 1.21
IS NULL THEN '0' 
ELSE SUM([Sales Amount (Actual)]) * 1.21
END FROM [DATABASE] 
WHERE [Posting Date] = '2015-07-01' AND [Location Code] = '121'  

更好的解决方案:

使用COALESCE

SELECT COALESCE(SUM([Sales Amount (Actual)]) * 1.21,0)
FROM [DATABASE] 
WHERE [Posting Date] = '2015-07-01' 
  AND [Location Code] = '121' 

COALESCE将返回第一个非空的参数

答案 3 :(得分:0)

尝试以下

SELECT SUM(ISNULL([Sales Amount (Actual)],0)) * 1.21
  FROM [DATABASE] 
  WHERE [Posting Date] = '2014-06-22' 
  AND [Location Code] = '129'