Tuesday, 5 March 2013

Using sql count/sum in a case statement in Oracle


Note :
For COUNT : need to use null  value you like to ignore
For SUM  : need to use null /zero value you like to ignore




select count(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;


select sum(case
             when retrieve_time is null then
              0
             else
              1
           END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;

 select sum(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30;



select to_char(CREATED_TIME, 'YYYY/MM/DD'),
       count(case
               when retrieve_time is null then
                null
               else
                1
             END) as retrieved
  from TABLE_A
 where CREATED_TIME > gmt_sysdate - 30
 group by to_char(CREATED_TIME, 'YYYY/MM/DD');

No comments: