我在Oracle数据库中有下表
tgt_tbl
--------------------------
id month
1 JAN-2015
1 FEB-2015
1 MAR-2015
...
...
2 APR-2016
2 MAY-2016
2 JUN-2016
...
...
3 JUL-2014
3 AUG-2014
3 SEP-2014
3 OCT-2014
...
我想将src_tbl中的行插入目标表并创建一个 from_date和thru_date之间每个月的行如下:
spec:
type: NodePort
ports:
- port: 27018
targetPort: 27017
protocol: TCP
任何建议都将不胜感激。
答案 0 :(得分:5)
select id, to_char( add_months(from_date, level - 1), 'MON-yyyy' ) as mth
from src_tbl
connect by level <= months_between(thru_date + 1, from_date)
and prior id = id
and prior sys_guid() is not null
;
注意:正如评论中所讨论的那样,我认为“环境”保证thru_date
永远不会超过任何from_date
的{{1}}。如果是,则此查询将生成一行(对于id
月),或许它应该不生成。理想情况下,逻辑条件由基表上的检查约束强制执行。
答案 1 :(得分:-1)
这是SQL SERVER版本。您可以确定找到Oracle CTE语法。 但递归逻辑保持不变。
create table tbl1(id int, fd date, td date)
insert into tbl1(id,fd,td)
Select 1,'1-1-2016','4-1-2016'
union all select 2,'6-1-2016','8-1-2016'
;with c1(fd,td,id,rowid)
AS
(
select fd,td,id,ROW_NUMBER() over (order by id) rowid from tbl1
),
c2(fd,td,id,rowid)
AS
(
select fd,td,id,rowid from c1-- where rowid=1
union all
select DATEADD(month,1,c2.fd),c1.td,c1.id,c2.rowid from c1
join c2 on c2.fd<c1.td and c1.id=c2.id
)
select * from c2 order by rowid,fd