PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

PostgreSQL utilizza il valore della riga precedente se mancante

Puoi combinare un self join e funzioni di Windows

Semplificando prendo questa tabella con questi valori di esempio:

create table t ( a int, b int);    
insert into t values 
( 1, 1),
( 2, Null),
( 3, Null),
( 4, 2 ),
( 5, Null),
( 6, Null);

Nella tua richiesta a è trunc_u e b è il tuo id .La query è:

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;

E risultati:

| A | B |
---------
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 2 |