Search code examples
sqlteradatawindow-functionsteradatasql

How to get the next value in a dynamic range?


I wish to get the next value in a dynamic range. Between all values existing up until point X (determined by column TimeDate) I want to get the next largest ValueDate if it exists. The lookup could be something like UNBOUNDED PRECEEDING AND CURRENT ROW and most likely sorted by TimeDate, but I've yet to figure out how to do this with either LAG/LEAD or FIRST/LAST VALUE.

Here's what the data looks like and what I want to achieve:

SomeIndex ValueDate TimeDate DesiredResult
1 13.02.2022 10.09.2023 NULL
1 21.03.2022 11.09.2023 NULL
1 17.01.2022 12.09.2023 13.02.2022
1 28.02.2022 13.09.2023 21.03.2022
1 19.12.2021 14.09.2023 17.01.2022
1 23.12.2021 15.09.2023 17.01.2022

Key note - even though ValueDate = '23.12.2021' is the next largest value after ValueDate = '19.12.2021', it doesn't "exist" yet based on the TimeDate column.

Here's some SQL to quickly cook up the data:

CREATE VOLATILE TABLE TempTable (
    SomeIndex INTEGER,
    ValueDate DATE FORMAT 'YYYY-MM-DD',
    TimeDate DATE FORMAT 'YYYY-MM-DD')
PRIMARY INDEX (SomeIndex)
ON COMMIT PRESERVE ROWS;

INSERT INTO TempTable VALUES(1,'2022-02-13','2023-09-10');
INSERT INTO TempTable VALUES(1,'2022-03-21','2023-09-11');
INSERT INTO TempTable VALUES(1,'2022-01-17','2023-09-12');
INSERT INTO TempTable VALUES(1,'2022-02-28','2023-09-13');
INSERT INTO TempTable VALUES(1,'2021-12-19','2023-09-14');
INSERT INTO TempTable VALUES(1,'2021-12-23','2023-09-15');

Solution

  • Could you try and achieve this using a co-related sub query instead ? I've tried as below ...

    SELECT a.SomeIndex, a.ValueDate, a.TimeDate, b.ValueDate AS DesiredResult
    FROM TempTable a LEFT JOIN TempTable b on b.TimeDate <= a.TimeDate
    AND b.ValueDate = ( SELECT MIN(ValueDate) 
                        FROM TempTable c 
                        WHERE c.ValueDate > a.ValueDate AND c.TimeDate <= a.TimeDate)
    ORDER BY a.TimeDate