在不同列中按日期创建开始和结束日期

时间:2019-02-05 18:48:30

标签: sql oracle

我有下表示例。我的示例可以包含许多cust_assgn_dts。

目标是为每个日期创建一个开始周期和结束周期。

ID CustID Start_DT   End_dt    Role       Cust_Assgn_dt     CustIds
 1  101   10/10/2018 11/13/2018 Primary   10/10/2018 8:35:24  98456
 1  101   10/10/2018 11/13/2018 Primary   10/10/2018 2:09:52  14687
 1  101   10/10/2018 11/13/2018 Primary   11/01/2018 2:10:42  15887
 1  101   10/10/2018 11/13/2018 Secondary 11/13/2018 9:12:00  15489
 1  101   10/10/2018 11/13/2018 Scheduler 10/10/2018 8:35:24  26987
 1  101   10/10/2018 11/13/2018 Scheduler 10/10/2018 2:09:52  26598

预期输出:(第一个StartCycle始终是Start_dt的日期)EndCycle则是下一个日期的前一天)

ID  StartCycle  EndCycle   Scheduler Primary Secondary Start_dt   End_dt
1   10/10/2018  10/31/2018  26598      14687           10/10/2018
1   11/01/2018  11/12/2018  26598      15887           10/10/2018
1   11/13/2018  12/31/9999  26598      15887   15489   10/10/2018 11/13/2018

我当前的查询:

SELECT *
FROM (
  SELECT *
  FROM (
        SELECT 
        A.ID,
        A.CUSTID
        A.START_DT,
        A.END_DT,
        A.CUSTIDS,
        A.ROLE
        ,TRUNC(A.CUST_ASSGN_DT) AS CUST_ASSGN_DT
        ,DENSE_RANK() OVER (PARTITION BY ID,ROLE, TRUNC(CUST_ASSGN_DT) ORDER BY CUST_ASSGN_DT DESC) RNK
        FROM  A
        WHERE 1=1
        AND A.ID = 101
            )
  WHERE 1=1
  AND RNK = 1
  )
  PIVOT    
 (
  MAX(CUSTIDS)
 FOR ROLE IN ('SCHEDULER' AS SCHEDULER,'PRIMARY' AS PRIMARY,'SECONDARY' AS SECONDARY)
 )

这给了我每个cust_assgn_dt的角色,但没有给我任何周期。

我要采用正确的方法还是应该采用其他方法?我使用的是pl / sql软件,但是在SQL oracle中编写的。

0 个答案:

没有答案