Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sum function ansd NULLS

Author  Topic 

pazzy11
Posting Yak Master

145 Posts

Posted - 2007-12-12 : 06:11:55
If i want to use the sum function but some of the fields are NULL
the sum returns as NULL ..

how can I avoid this ?

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-12-12 : 06:14:09
sum(coalesce(col1,0))+sum(coalesce(col2,0))+...

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-12-12 : 06:20:22
sum(coalesce(col1, 0) + coalesce(col2, 0) + ... )



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

pazzy11
Posting Yak Master

145 Posts

Posted - 2007-12-12 : 06:21:29
So
[CODE]
select a ,
b,
sum(c) as 'TOTAL'
[/CODE]

becomes
[CODE]
select a ,
b,
sum(coalesce(c,0)) as 'TOTAL'
[/CODE]
?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-12-12 : 06:22:18
shortcut of mine?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

pazzy11
Posting Yak Master

145 Posts

Posted - 2007-12-12 : 06:23:53
yes but i was checking that is correct yes ?

sum(coalesce(c,0)) as 'TOTAL' ??

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-12-12 : 06:24:02
quote:
Originally posted by pazzy11

So
[CODE]
select a ,
b,
sum(c) as 'TOTAL'
[/CODE]

becomes
[CODE]
select a ,
b,
sum(coalesce(c,0)) as 'TOTAL'
[/CODE]
?



If you sum only one column, by default NULL values are omitted

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -