1. 程式人生 > >將時間點的數據變成時間段的數據

將時間點的數據變成時間段的數據

nvl 創建 family eat color bsp bold 時間段 microsoft

已知數據如下:
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;

將時間點的數據變成時間段的數據