sql - Oracle query to get month wise data and give 0 for month not available -


following table data

time_stamp     name 01-mar-14      02-mar-14      b 02-mar-14      c 01-may-14      d 02-may-14      e 01-jun-14      f 

output required:

(3,0,2,1) (month wise count 0 if month doesn't exist) 

i have created following query :

select   listagg(count(1),',') within group (order extract(month time_stamp))  ps_bqueues_host  time_stamp between to_date('01-mar-14', 'dd-mon-yy') ,   to_date('01-jun-14', 'dd-mon-yy') group extract(month time_stamp) 

this gives me output :

(3,2,1) (month of apr 0 not there). 

please suggest how group on months.

thanks.

you should join original table table months in given period. if inside 1 year we need 1,2,3,...12 sequence.

select   listagg(count(name),',') within      group (order m.rn)        (select *  ps_bqueues_host        time_stamp          between to_date('01-mar-14', 'dd-mon-yy')          ,     to_date('01-jun-14', 'dd-mon-yy')       )    right join       (select level rn dual connect level <= 12) m      on m.rn=extract(month time_stamp)  m.rn between extract(month to_date('01-mar-14', 'dd-mon-yy'))            ,  extract(month to_date('01-jun-14', 'dd-mon-yy')) group m.rn 

sqlfiddle demo


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -