Home > Net >  postgres How to join data and replace null value
postgres How to join data and replace null value

Time:07-22

i am still newbie in sql and i have stuck in this Postgres sql problem, can you help me

i have data table like this

NIk GROUP A B C
201212003 ENG M
201212003 ENG P
201301005 ENG P
201301005 ENG S

expected result:

NIk GROUP A B C
201212003 ENG M P
201301005 ENG P S

i already try to use any join cant get the result. Please help me

CodePudding user response:

If that is your original data, you need to split it into 3 tables, and then do the join.

with table_a as (
    select "Nlk", "GROUP", "A"
    from original_data
    where "A" is not null
), table_b as (
    select "Nlk", "GROUP", "B"
    from original_data
    where "B" is not null
), table_c as (
    select "Nlk", "GROUP", "C"
    from original_data
    where "C" is not null
)
select "Nlk", "GROUP", "A", "B", "C"
from table_a
full join table_b using ("Nlk", "GROUP")
full join table_c using ("Nlk", "GROUP")

" after ENG in GROUP is ignored

CodePudding user response:

Aggregate:

select NIk, "GROUP", max(A) A, max(B) B, max(C) C
from mytable
group by NIk, "GROUP"
  • Related