with siv (dt_from, agreement_version, line_version, agreement_is_actual, siv_is_actual, cost, prob) as (VALUES ('2025-01-01'::date, 1, 1, true, true, 100, 100), ('2025-02-01', 1, 10, false, true, 200, 10), ('2025-02-01', 1, 12, true, true, 200, 100), ('2025-03-01', 2, 20, true, true, 100, 100), ('2025-03-01', 2, 21, true, true, 150, 100), ('2025-02-15', 3, 30, true, true, 300, 100), ('2025-04-01', 4, 40, false, true, 100, 100) ) SELECT (LAST_VALUE (dt_from) OVER (ORDER BY dt_from, agreement_version,line_version RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)), --coalesce((LEAD(dt_from) OVER (ORDER BY dt_from, agreement_version,line_version)), (select max(dt) from elma.mv_dt)) dt_next, * from siv