已知数据如下:
PC E D
工 5 2016-09-01
工 6 2016-09-30
公 5 2016-09-01
公 6 2017-09-30
加入查询开始日期是2016-09-01,结束日期2016-10-07
希望将上面数据变成:
PC E S N
工 5 2016-09-01 2016-09-30
工 6 2016-09-30 2016-10-07
公 5 2016-09-01 2016-10-07
--创建测试表 create table tmp as select '工' PC, 5 E, to_date('2016-09-01','yyyy-mm-dd') D from dual union all select '工' PC, 6 E, to_date('2016-09-30','yyyy-mm-dd') D from dual union all select '公' PC, 5 E, to_date('2016-09-01','yyyy-mm-dd') D from dual union all select '公' PC, 6 E, to_date('2017-09-30','yyyy-mm-dd') D from dual; --写法1: select pc,e,case when to_date('2016-09-01','yyyy-mm-dd') >= d then to_date('2016-09-01','yyyy-mm-dd') else d end s, nvl(lead(d,1)over(partition by pc order by d),to_date('2016-10-07','yyyy-mm-dd')) as d from tmp where d <= to_date('2016-10-07','yyyy-mm-dd') order by pc,s; --写法2: select pc,e,d as s, nvl(lead(d,1)over(partition by pc order by d),to_date('2016-10-07','yyyy-mm-dd')) as n from tmp where d <=to_date('2016-10-07','yyyy-mm-dd') order by pc,s;