Home > Net >  repeat value of a row when other row is null
repeat value of a row when other row is null

Time:03-10

I have a table like this:

 id | nu_cns | nu_cpf | co_dim_tempo | sifilis | hiv
908 |   null |    347 |            1 |       y |   n
908 |    708 |   null |            2 |       y |   y
908 |    708 |   null |            3 |       y |   y

I need to repeat the fields' values of nu_cns and nu_cpf when these fields are null, for example:

 id | nu_cns | nu_cpf | co_dim_tempo | sifilis | hiv
908 |   *708 |    347 |            1 |       y |   n
908 |    708 |   *347 |            2 |       y |   y
908 |    708 |   *347 |            3 |       y |   y

CodePudding user response:

You can use last_value with frame clause rows between unbounded preceding and current row:

select id, first_value(nu_cns) over (order by co_dim_tempo rows between unbounded preceeding and current row)
from your_table 
order by co_dim_tempo

CodePudding user response:

If you're fine with any value, just do..

select *, 
       max(nu_cns) over (partition by id),
       max(nu_cpf) over (partition by id)  
from t;
  • Related