0

I have a table with all the ids in an array like format and another table that matches the ids with the names. I'm required to write a query that creates creates a new table with 2 columns : ids (which is an array of ids) and names (an array with the corresponding names of the ids).

INPUT TABLES :

main

ids
---------
i1 | i2
i2 | i3
i3 

agents

ids    names
--------------
i1     agent1
i2     agent2
i3     agent3

OUTPUT :

ids        names
----------------------------
(i1, i2)   (agent1, agent2)
(i2, i3)   (agent2, agent3)
(i3)       (agent3)

Output can also be in this format : i1 | i2 for all the elements, that would be fine as well, not absolutely necessary that they should be converted to arrays as I've done below.

I managed to convert the | separated ids column to arrays, but couldn't progress after that.

string_to_array(substr(translate(translate(
  main.ids, '|', ','), ' ', ''), 1, length(main.ids) - 3), ',') 
  AS ids

1 Answer 1

1

Use the unnest function to expand the array into rows, then join with the other table and finally use array_agg to aggregate rows into single value:

SELECT 
'( ' || main.ids || ' )' AS ids,
'( ' || array_to_string(
  (SELECT array_agg(agents.names) 
    FROM unnest(
      string_to_array( replace(main.ids,' ',''), '|')
    ) as tmp(temp_main_ids) 
    LEFT JOIN agents ON tmp.temp_main_ids = agents.ids
  ),' | ') 
|| ' )' AS names
FROM main
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks a lot for your reply. Can you add the table name with the parameters, like usemain_ids and agent_ids for these columns. This was like a sample example I created and I'm finding it hard to replace this.
I am not sure that I follow you - but I prefixed the columns with their respective table name.

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.