简体   繁体   中英

Oracle query period data to month

I have a table where there is a period column stored in format YYYYMM'||-||'YYYYMM (Ex : 201111-201203 ). I need a SQL query to whcih result in row wise data with each row repsenting month in format YYYYMM .

INPUT

201111-201203

OUTPUT

201111
201112
201201
201202
201203

Analyse this code:

select 
    id, to_char(add_months(to_date(substr(interv,1,6),'yyyymm'), i),'yyyymm')
from
   (Select level-1 as i from dual connect by level <= 50)
   join
   (
   select 1 as id,'201111-201203' as interv from dual
   union all
   select 2, '201201-201301' from dual
   )
on add_months(to_date(substr(interv,1,6),'yyyymm'), i) <=
    to_date(substr(interv,-6),'yyyymm')
order by 1,2;

Forget joins and PL/SQL:

-- List of months between dates --
SELECT to_char( add_months( start_date, LEVEL-1 ), 'YYYYMM' ) list_of_months
 FROM 
 (
  SELECT to_date('201111', 'YYYYMM') start_date,
         to_date('201203', 'YYYYMM') end_date
    FROM dual
 )
  CONNECT BY LEVEL <= MONTHS_BETWEEN(Trunc(end_date,'MM'), Trunc(start_date,'MM'))+1
 /

LIST_OF_MONTHS
--------------
201111
201112
201201
201202
201203

use this snippet to develop your code , you can create a function or a procedure to get output as you want

  declare

  v_from_date date;
  v_to_date   date;

  v_time varchar2(20);

begin

  v_time := '201111-201203';


  v_from_date := to_date(substr(v_time, 0, 6), 'YYYYMM');
  v_to_date   := to_date(substr(v_time, 8, 6), 'YYYYMM');

  while v_from_date <= v_to_date loop

    dbms_output.put_line(v_from_date);

    v_from_date := ADD_MONTHS(v_from_date, 1);

  end loop;

end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM