views:

231

answers:

2

I have a a table with a column groups INTEGER NULL. It has values

groups

5
7
<NULL>

If I do a select sum(groups) form table_name
I would get 12. How can I get null, when the column being summed has a null.

+3  A: 

One option:

CASE WHEN COUNT(*) = COUNT(groups) THEN SUM(groups) ELSE NULL END
Ants Aasma
Looks good: count(*) gives the total number of rows, count(groups) gives the number of non-null groups. If these are different then you must have a null or two.
pjp
Thank you. Simple and works.
uswaretech
+1  A: 
select
  case when exists (select groups from table where groups = null) then null
       else select sum(groups) from table
  end as sum
Zed
+1 My thoughts exactly, beat me to it :)
Roee Adler
You can still come up with a nice stored procedure using cursors :)
Zed