Search code examples
sqlpostgresqlaggregate-functionsmissing-datasql-null

repeat value of a row when other row is null


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

Solution

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

    select id, first_value(nu_cns) 
      over (partition by id order by nu_cns rows between unbounded preceding and current row)
      from my_table