线索和案例表达

Lead and case expression

我有这个 table:

ID    Date
-----------------
1     1/1/2019
1     1/15/2019

预期输出:

ID   DATE      LEAD_DATE  
-------------------------
1    1/1/2019  1/14/2019
1    1/15/2019  SYSDATE

SQL:

SELECT 
    *,
    CASE 
        WHEN LEAD (a.date) OVER (PARTITION BY a.ID ORDER BY a.date) = TRUNC(a.date) THEN NULL
        ELSE LEAD (a.date) OVER (PARTITION BY a.id ORDER BY a.date) - NUMTODSINTERVAL(1,'second')
    END AS LEAD_DT
 FROM a

结果:

ID  DATE      LEAD_DATE
-------------------------
 1  1/1/2019    1/14/2019
 1  1/15/2019   

case表达式null时可以加上系统日期吗?

使用NVL

SELECT 
    a.*,
    NVL(CASE 
        WHEN LEAD (a.date) OVER (PARTITION BY H.ID ORDER BY a.date) = TRUNC(a.date) THEN NULL
        ELSE LEAD (a.date) OVER (PARTITION BY a.id ORDER BY a.date) - NUMTODSINTERVAL(1,'second')
    END, SYSDATE) AS LEAD_DT
FROM a

或者,更好的是:

SELECT 
    a.*,
    CASE LEAD (a.date) OVER (PARTITION BY a.ID ORDER BY a.date)
        WHEN TRUNC(a.date) THEN SYSDATE
        WHEN NULL THEN SYSDATE
        ELSE LEAD (a.date) OVER (PARTITION BY a.id ORDER BY a.date) - NUMTODSINTERVAL(1,'second')
    END AS LEAD_DT
 FROM a

使用COALESCE:.

SELECT a.*,
  CASE COALESCE(LEAD("Date") OVER (PARTITION BY ID ORDER BY "Date") - "Date", 0)
    WHEN 0 THEN SYSDATE
    ELSE LEAD("Date") OVER (PARTITION BY ID ORDER BY "Date") - INTERVAL '1' SECOND
  END AS LEAD_DT
FROM a