0

I have a table1 and want to insert values into a table2 in postgres. Table1 is looking like this:

Table1:
    z  a b    c
    q1 x 10   5
    q1 y null 20
    q1 y null null
    q2 x 20   10
    q2 y null 15
    q2 y null 25

Values of Table1 should be inserted in a table2 like this:

Table2:
    z  b  c1 c2
    q1 10 20 null
    q2 20 15 25

Thus differnt values in table1.z should be one row in table 2. (table2.b = table1.b WHERE table1.a = x) (table2.c = table1.c WHERE table1.a = y)

I tried my best to keep it understandable

2
  • If I followed you correctly, shouldn't second row in table2 be q2 20 25 15 instead of q2 20 15 15? Commented Nov 19, 2019 at 8:31
  • yea, thank you, i corrected to q2 20 15 25 Commented Nov 19, 2019 at 8:35

1 Answer 1

1

This is a bit akward but it can be done. You would need to rank the records in an inner query, and then do conditional aggregation in the outer query:

insert into table2(z, b, c1, c2)
select 
    z,
    max(case when a = 'x' and rnb = 1 then b end),
    max(case when a = 'y' and rnc = 1 then c end),
    max(case when a = 'y' and rnc = 2 then c end)
from (
    select
        t.*,
        row_number() over(partition by z, a order by b) rnb,
        row_number() over(partition by z, a order by c) rnc
    from table1 t
) t
group by z

Demo on DB Fiddle:

z  |  b | c1 |   c2
:- | -: | -: | ---:
q1 | 10 | 20 | null
q2 | 20 | 15 |   25
Sign up to request clarification or add additional context in comments.

2 Comments

thx for your help, i will try this. but what does rnb = 1... mean?
@Pseudalitos: rnb is the alias for one of the ranks affected in the inner query. You can run the subquery independantly to see what it returns.

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.