0

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

输入

201111-201203

输出

201111
201112
201201
201202
201203
4

3 回答 3

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;
于 2013-02-19T06:39:48.720 回答
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
于 2013-02-19T18:27:44.960 回答
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;
于 2013-02-19T06:37:44.060 回答