将时间点的数据变成时间段的数据

已知数据如下:
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;
原文地址:https://www.cnblogs.com/huangbiquan/p/7783297.html