Tuesday, 16 October 2007

SUMming in oracle

In oracle, infact in all databases that follow the standards, when you sum on a column that contains null data, the rows are ignored, for ages i couldn't find out how to sum the data and return null if there were "unknown" values in the table.

Here is the solution

select decode(

count(1),

sum(decode(comm,null,0,1)),

sum(comm),

null) comm_total

from emp;


here is the process behind the code above,

1 Count all rows
2 Count all rows that are not null
3 If the results from 1 and 2 are the same then return the sum else return null.