Oracle
 sql >> Database >  >> RDS >> Oracle

Generazione di righe separate per ogni mese in un intervallo di date

Puoi utilizzare una semplice tecnica di generazione di righe utilizzando CONNECT BY sintassi:

with sample_data as 
  (select 'XXA' id, to_date('1/23/14','MM/DD/RR') start_date, to_date('3/12/14','MM/DD/RR') end_date from dual)
select id, to_char(add_months(start_date,level - 1),'Month YYYY') date_column
from sample_data
connect by level <= extract(month from end_date) - extract(month from start_date) + 1;

Modifica Aggiunta di DISTINCT dovrebbe consentire che funzioni su più righe, credo, anche se sarei interessato a essere smentito.Modifica 2 Esempio modificato per gestire più anni (avresti dovuto farlo originariamente). (Vedi esempio http://sqlfiddle.com/#!4/9eecb/4097/ 0 .)

with sample_data as 
  ( select 'XXA' id, to_date('1/23/14','MM/DD/RR') start_date, to_date('3/12/15','MM/DD/RR') end_date from dual union all    
    select 'XXB' id, to_date('4/12/14','MM/DD/RR') start_date, to_date('6/18/15','MM/DD/RR') end_date from dual )
select distinct 
  id,
  to_char(add_months(start_date,level - 1),'Month YYYY') date_column,
  add_months(start_date,level -1) sortkey
from sample_data
connect by level <= ceil(months_between(trunc(end_date,'MM'), trunc(start_date,'MM'))) + 1
order by id, sortkey;

Nel mio DB sandbox questo produce:

ID  DATE_COLUMN     SORT_COL
XXA January   2014  23-JAN-2014 00:00:00
XXA February  2014  23-FEB-2014 00:00:00
XXA March     2014  23-MAR-2014 00:00:00
XXB April     2014  12-APR-2014 00:00:00
XXB May       2014  12-MAY-2014 00:00:00
XXB June      2014  12-JUN-2014 00:00:00