Oracle查询期间数据到月份

时间:2013-02-19 06:09:28

标签: sql oracle

我有一个表格,其中有一个以YYYYMM'||-||'YYYYMM格式存储的句号列(例如:201111-201203)。我需要一个SQL查询来导致行方式数据,每行以格式YYYYMM表示一个月份。

INPUT

201111-201203

输出

201111
201112
201201
201202
201203

3 个答案:

答案 0 :(得分:1)

分析此代码:

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;

答案 1 :(得分:1)

忘记加入和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

答案 2 :(得分:0)

使用此代码片段开发代码,您可以根据需要创建函数或过程以获取输出

  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;