My Select SUM query returns null. It should return 0

后端 未结 5 799
自闭症患者
自闭症患者 2020-12-09 01:56

I\'m trying to sum up Customer balances using the following query:

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

However, if

相关标签:
5条回答
  • 2020-12-09 02:02

    Try this:

    select sum(IsNull(balance,0)) from mytable where customer = 'john' 
    
    0 讨论(0)
  • 2020-12-09 02:07
    select coalesce(sum(coalesce(balance,0)),0) from mytable where customer = 'john' 
    
    0 讨论(0)
  • 2020-12-09 02:14

    Try this:

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

    This should do the work. The coalesce method should return the 0.

    0 讨论(0)
  • 2020-12-09 02:16

    That's not a problem. If there are no rows, sum() will return null. It will also return null if all rows have a null balance.

    To return zero instead, try:

    select isnull(sum(balance),0) from mytable where customer = 'john' 
    
    0 讨论(0)
  • 2020-12-09 02:24

    Maybe you are thinking of COUNT's behaviours?

    COUNT(Field) will return 0 but SUM(Field) returns NULL if there are no matching rows.

    You need an ISNULL or COALESCE

    COALESCE or ISNULL

    0 讨论(0)
提交回复
热议问题