2

I have a table in PostgreSQL, with two columns: id and nodes. id is of type bigint, as it is the primary key in the table. nodes is an array of bigint. I would like to create a new table, where the nodes in the node arrays are the keys and the only other column is an array of ids that correspond to that node.

So let's say the original table is like this:

id | nodes
1  | {200, 300, 400}
2  | {200, 300, 400}

then the new table should be like:

node | ids
200  | {1, 2}
300  | {1, 2}
400  | {1, 2}

2 Answers 2

4

demo: db<>fiddle

SELECT node, array_agg(id) as ids
FROM (
    SELECT id, unnest(nodes) as node 
    FROM nodes
)s 
GROUP BY node
ORDER BY node

unnest() expands the array into one row per element.

Then you are able to GROUP by the array elements and aggregate the ids with array_agg


In your case this can be shortened to a query without any subquery or join:

SELECT unnest(nodes) as node, array_agg(id) as ids 
FROM nodes
GROUP BY node
ORDER BY node 
Sign up to request clarification or add additional context in comments.

Comments

1

You can unnest and re-aggregate. No subquery is necessary:

with t as (
      select 1 as id, array[200, 300, 400] as nodes union all
      select 2 as id, array[200, 300, 400] as nodes 
     )
select node, array_agg(t.id)
from t cross join
     unnest(nodes) node
group by node

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.