Home All Groups Group Topic Archive Search About

Adding with NULL values

Author
7 Jul 2005 3:53 PM
ninel gorbunov
I have 3 columns that need to be summed up, but any one of these can contain
a NULL value.

Col1  Col2   Col3    Col4
A     2.67    4.7     2.8
B     6.2     NULL    2.6
C     12.4    NULL    NULL

How can I sum them up to look like this?

A = 10.17
B = 8.8
C = 12.4

Thanks,
Ninel

--
Message posted via http://www.sqlmonster.com

Author
7 Jul 2005 4:02 PM
Michael C#
COALESCE(Col2, 0) + COALESCE(Col3, 0) + COALESCE(Col4, 0)

Show quote
"ninel gorbunov" <fo***@SQLMonster.com> wrote in message
news:50F863E0C75B0@SQLMonster.com...
>I have 3 columns that need to be summed up, but any one of these can
>contain
> a NULL value.
>
> Col1  Col2   Col3    Col4
> A     2.67    4.7     2.8
> B     6.2     NULL    2.6
> C     12.4    NULL    NULL
>
> How can I sum them up to look like this?
>
> A = 10.17
> B = 8.8
> C = 12.4
>
> Thanks,
> Ninel
>
> --
> Message posted via http://www.sqlmonster.com
Author
7 Jul 2005 4:03 PM
--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications.  It is very hard to debug code when you do not let us
see it.

SELECT col1, COALESCE(col2, 0) + COALESCE(col3, 0) + COALESCE(col4, 0)
  FROM Foobar;

But you did not tell us what to do with all NULLs.  Is it zero or NULL?
Author
7 Jul 2005 4:04 PM
Ravi
Try ISNULL(Col2,0)+ISNULL( Col3,0)+ISNULL( Col4,0)

--
Thanks & Rate the Postings.
-Ravi-


Show quote
"ninel gorbunov" wrote:

> I have 3 columns that need to be summed up, but any one of these can contain
> a NULL value.
>
> Col1  Col2   Col3    Col4
> A     2.67    4.7     2.8
> B     6.2     NULL    2.6
> C     12.4    NULL    NULL
>
> How can I sum them up to look like this?
>
> A = 10.17
> B = 8.8
> C = 12.4
>
> Thanks,
> Ninel
>
> --
> Message posted via http://www.sqlmonster.com
>

AddThis Social Bookmark Button