Skip to content
Advertisement

Lead and case expression

I have this table:

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

Expected output:

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

Results:

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

Can I add the system date when null in the case expression?

Advertisement

Answer

Use 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

Or, better yet :

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement