[英]Oracle query period data to month
I have a table where there is a period column stored in format YYYYMM'||-||'YYYYMM
(Ex : 201111-201203
). 我有一个表,其中有一个以
YYYYMM'||-||'YYYYMM
格式存储的句号列(例如: 201111-201203
)。 I need a SQL query to whcih result in row wise data with each row repsenting month in format YYYYMM
. 我需要一个SQL查询来导致行方式数据,每行以YYYYMM格式
YYYYMM
每月YYYYMM
。
INPUT INPUT
201111-201203
OUTPUT 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: 忘记连接和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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.