创建日期的开始日期和结束日期字段

时间:2018-10-10 19:24:20

标签: sql oracle

我有下表

START_DT   END_DT    ID     NAME    ROLE       CUST_DT
6/22/18              1245   SMITH   CUST1    7/31/18 12:55:42
6/22/18              1245   SMITH   CUST1    7/31/18 13:56:50
6/22/18              1245   JACK    CUST2    7/31/18 13:56:50
5/1/18     5/30/18   5156   ROBERT  CUST1    5/01/18 12:25:25
5/1/18     5/30/18   5156   JOHN    CUST2    5/02/18 12:25:88

我想要下面的输出

 ID     NAME   ROLE   CUST_START_DT        CUST_END_DT  
1245   SMITH   CUST1   7/31/18 12:55:42    7/31/18 13:56:49   
1245   SMITH   CUST1   7/31/18 13:56:50           
1245   JACK    CUST2   7/31/18 13:56:50    
5156   ROBERT  CUST1   5/01/18 12:25:25    5/02/18 12:25:87     
5156   JOHN    CUST2   5/02/18 12:25:88  

我不确定从哪里开始,也许我可以提前/滞后功能吗?

1 个答案:

答案 0 :(得分:1)

尝试在下面的查询中获得预期的输出

create table start_end
(ID NUMBER,
NAME VARCHAR2(12),
ROLE VARCHAR2(10),
CUST_DT TIMESTAMP);


select id,name,role, CUST_DT CUST_START_DT, 
case when lead (CUST_DT) OVER ( partition by ID ORDER BY CUST_DT)=CUST_DT 
THEN NULL 
ELSE lead (CUST_DT) OVER ( partition by ID ORDER BY CUST_DT) - numToDSInterval( 1, 'second' )
END AS CUST_END_DT  
from start_end;