2

Table has 2 array columns Key and Value. For EG:

ID Key Value
1 a,b,c,d 1,2,3,4
2 b,c 7,8
3 a,c 0,9
4 b,c,d 3,7,1

Need to map the Key to the Value and split it into separate columns

ID a b c d
1 1 2 3 4
2 7 8
3 0 9
4 3 7 1

1 Answer 1

3

You can convert both string into arrays, unnest the arrays and aggregate those key/value pairs back into a JSON value. That value then can be used to extract the four keys again:

select id, 
       cols ->> 'a' as a,
       cols ->> 'b' as b,
       cols ->> 'c' as c,
       cols ->> 'd' as d
from (
        select id, 
               (select jsonb_object_agg(k,v)
                from unnest(string_to_array(key,','), 
                            string_to_array(value, ',')) as x(k,v)) as cols
        from the_table        
) x
order by id;

Online example

I would probably create a function to make the code a bit easier to read.

Sign up to request clarification or add additional context in comments.

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.