1

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
4
  • Could you have different sets of values in nu_cns and nu_cpf for a given id ? Commented Mar 9, 2022 at 16:05
  • @PhilCoulson sometimes yes, but, if the result list only one, is ok. Commented Mar 9, 2022 at 16:08
  • So if you can have multiple values, how do you decide which value replaces the nulls? Commented Mar 9, 2022 at 16:16
  • @PhilCoulson any value can replace the null value. is very rare more than one value Commented Mar 9, 2022 at 16:17

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

syntax error at or near "preceeding" LINE 1: ...ver (order by co_dim_tempo rows between unbounded preceeding...
@ItaloRodrigo of course it's a typo, should be preceding, sorry :>
Works fine like this: select id, first_value(nu_cns) over (partition by id order by nu_cns rows between unbounded preceding and current row) can you edit your answer, please?
@ItaloRodrigo, sure. Note that it would also work if you changed the ordering with desc
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.