Můžete zkombinovat self join s okénkovými funkcemi.
Pro jednoduchost zde máme tabulku se vzorovými hodnotami:
create table t ( a int, b int); insert into t values (1, 1), (2, Null), (3, Null), (4, 2), (5, Null), (6, Null);Ve vašem dotazu je a hodnota trunc_u a b je vaše id. Dotaz je:
with cte as ( select t1.a, coalesce(t1.b, t2.b, 0) as b, rank() OVER (PARTITION BY t1.a ORDER BY t2.a DESC) as pos from t t1 left outer join t t2 on t2.b is not null and t2.a < t1.a ) select a, b from cte where pos = 1;A výsledek:
| A | B | |--------- | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 2 | | 6 | 2 |