我的Select SUM查询返回null。它应该返回0

时间:2013-06-11 15:44:08

标签: sql sql-server

我正在尝试使用以下查询来总结客户余额:

select sum(balance) from mytable where customer = 'john' 

但是,如果客户没有余额(即mytable表中没有匹配的行),我的查询将返回null而不是0.问题是什么?

5 个答案:

答案 0 :(得分:79)

试试这个:

select COALESCE(sum(balance),0) from mytable where customer = 'john' 

这应该做的工作。 coalesce方法应该返回0。

答案 1 :(得分:12)

这不是问题。如果没有行,sum()将返回null。如果所有行都有null余额,它也会返回null

要返回零,请尝试:

select isnull(sum(balance),0) from mytable where customer = 'john' 

答案 2 :(得分:3)

select coalesce(sum(coalesce(balance,0)),0) from mytable where customer = 'john' 

答案 3 :(得分:1)

试试这个:

select sum(IsNull(balance,0)) from mytable where customer = 'john' 

答案 4 :(得分:1)

也许您正在考虑COUNT的行为?

如果没有匹配的行,

COUNT(Field)将返回0,但SUM(Field)会返回NULL

您需要ISNULLCOALESCE

COALESCEISNULL

相关问题