Generate series of months for every row in Oracle

安稳与你 提交于 2021-02-10 23:47:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!