0

I have the following table:

"Id"|                  "Data"
====+================================================
1   | { "emp": [ 
    |            {"id": "a1", "otherdata": "other"}, 
    |            {"id": "a2", "otherdata": "other"} 
    |          ]
    | }
----+------------------------------------------------
2   | { "emp": [ 
    |            {"id": "b1", "otherdata": "other"}, 
    |            {"id": "b2", "otherdata": "other"} 
    |          ]
    | }
-----------------------------------------------------

Where "Data" is jsonb.

I need to create a temporary table of this type:

"Id"| "Emp"
====+=============
1   | {"a1", "a2"}
----+-------------
2   | {"b1", "b2"}

How can I do this?

1 Answer 1

1

Use jsonb_to_recordset to extract the array values to rows, group them, then back to an array using array_to_json.

SELECT a.id, array_to_json(array_agg(b.id)) AS emp
FROM mytable a
CROSS JOIN jsonb_to_recordset(a.data->'emp') AS b(id text)
GROUP BY a.id;

See SQL Fiddle

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.