Puede combinar funciones de autounión y de Windows
Simplificando, tomo esta tabla con estos valores de muestra:
create table t ( a int, b int);
insert into t values
( 1, 1),
( 2, Null),
( 3, Null),
( 4, 2 ),
( 5, Null),
( 6, Null);
En su consulta a
es trunc_u
y b
es tu id
.La consulta es:
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;
Y resultados:
| A | B |
---------
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 2 |