问题
I am porting PostgreSQL select statement to Oracle. I cannot figure out how to re-write the following into Oracle syntax:
select
id,
generate_series(date_trunc('month', st_date),
en_date,'1 month')::date as dist_date
from
tst
I have a basic idea how I can generate range of months in Oracle, but I think different approach is neeeded as I don't see a way how to plug the following into my sql:
select
add_months(trunc(sysdate, 'month'), level)
from dual
connect by level <=
months_between(sysdate, to_date('2013-01-01','yyyy-mm-dd'));
Sample data:
create table tst (
id int,
st_date date,
en_date date);
insert into tst values(1, to_date('2014-02-15','yyyy-mm-dd'), to_date('2014-07-01','yyyy-mm-dd'));
insert into tst values(2, to_date('2014-03-15','yyyy-mm-dd'), to_date('2014-04-01','yyyy-mm-dd'));
Output:
1;"2014-02-01"
1;"2014-03-01"
1;"2014-04-01"
1;"2014-05-01"
1;"2014-06-01"
1;"2014-07-01"
2;"2014-03-01"
2;"2014-04-01"
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0
回答1:
This should do the trick (ignore the with clause; it's just mimicking your tst table without having to physically create the table):
with tst as (select 1 id, to_date('2014-02-15','yyyy-mm-dd') st_date, to_date('2014-07-01','yyyy-mm-dd') en_date from dual union all
select 2 id, to_date('2014-03-15','yyyy-mm-dd') st_date, to_date('2014-04-01','yyyy-mm-dd') en_date from dual)
select id, add_months(trunc(st_date, 'month'), level -1) mnth
from tst
connect by level <= months_between(trunc(en_date, 'mm'), trunc(st_date, 'mm')) + 1
and prior id = id
and prior dbms_random.value is not null;
ID MNTH
---------- ----------
1 2014-02-01
1 2014-03-01
1 2014-04-01
1 2014-05-01
1 2014-06-01
1 2014-07-01
2 2014-03-01
2 2014-04-01
来源:https://stackoverflow.com/questions/28896681/generate-series-of-months-for-every-row-in-oracle