Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SUM so that NULL in columns make sum NULL

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.

like image 628
agiliq Avatar asked Aug 17 '09 16:08

agiliq


2 Answers

One option:

CASE WHEN COUNT(*) = COUNT(groups) THEN SUM(groups) ELSE NULL END
like image 151
Ants Aasma Avatar answered Oct 21 '22 11:10

Ants Aasma


select
  case when exists (select groups from table where groups is null) then null
       else select sum(groups) from table
  end as grp_sum
like image 40
Zed Avatar answered Oct 21 '22 12:10

Zed