我正在将PostgreSQL select语句移植到Oracle。我无法弄清楚如何将以下内容重写为Oracle语法:
select
id,
generate_series(date_trunc('month', st_date),
en_date,'1 month')::date as dist_date
from
tst
我有一个基本的想法,我如何在Oracle中生成各种月份,但我认为需要采用不同的方法,因为我没有看到如何将以下内容插入到我的SQL中的方法:
select
add_months(trunc(sysdate, 'month'), level)
from dual
connect by level <=
months_between(sysdate, to_date('2013-01-01','yyyy-mm-dd'));
示例数据:
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'));
输出:
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企业版11.2.0.3.0版
答案 0 :(得分:1)
这应该可以解决问题(忽略with子句;它只是模仿你的tst表而不必实际创建表):
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