Solved

# SQL select sum() ...ignoring null's

Posted on 2003-10-28
Medium Priority
2,238 Views
i have a table test1 (a int)
there are following values:
1
2
3
4
null

now i want select the sum of the column a, i do:
select sum(case when a is null then 0 end) from test1

should be 10 ..but it doesnt run how i specified. i want that the null is ignored. how do i do that?

also i want calculate the average of the table above. there are 4 times a value set, (1+2+3+4) / 4 = 2.5

thx a lot
0
Question by:soci28

Assisted Solution

AndrewKT earned 200 total points
ID: 9633713
Your logic is missing a small item:

create table #test (a int null)

insert into #Test values (1)
insert into #Test values (2)
insert into #Test values (3)
insert into #Test values (4)
insert into #Test values (null)

select sum(case when a is null then 0 else a end) from #test

You gave the sum function a value only when a is null.
0

LVL 50

Assisted Solution

ID: 9633717
you don't need the case

select sum(a.int),avg(a.int)

will ignore the null values  in the columns from the calculations automatically..
0

LVL 18

Accepted Solution

ID: 9633718
SELECT avg(a),sum(a) from test1
0

LVL 18

Expert Comment

ID: 9633727
Pipped at the post again by lowfat ;)
0

Author Comment

ID: 9633869
is there a way to find out the average, if the table has more columns than one?

table test1 (a int, b int, c int, d int)
a  b  c  d
2  4  9  null

==> average should be 5 .. how do i find that?
0

LVL 18

Expert Comment

ID: 9633948
select (isnull(a,0)+isnull(b,0)+isnull(c,0)+isnull(d,0)) /
( case when a is null 0 else 1 end+case when b is null 0 else 1 end+case when c is null 0 else 1 end+case when d is null 0 else 1 end)
0

LVL 50

Expert Comment

ID: 9639082
shogun's solution is the only way for sql server although i believe oracle has
function which work "on" a row..
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
###### Suggested Courses
Course of the Month17 days, 4 hours left to enroll