dbfiddle here: https://dbfiddle.uk/?rdbms=postgres_10&fiddle=5924abbdad955e159de7f3571ebbac5a
Say I've a table
CREATE TABLE yewu (
id serial PRIMARY KEY,
org varchar(50),
data jsonb
);
I want to update table
id org data
1 OA [{"profiles": [{"id": 1}, {"id": 2}]}, {"profiles": [{"id": 3}, {"id": 4}]}]
2 OB [{"profiles": [{"id": 1}, {"id": 2}]}, {"profiles": [{"id": 3}, {"id": 4}]}]
to
id org data
1 OA [{"profiles": [{"id": 1,"org":"OA"}, {"id": 2,"org":"OA"}]}, {"profiles": [{"id": 3,"org":"OA"}, {"id": 4,"org":"OA"}]}]
2 OB [{"profiles": [{"id": 1,"org":"OB"}, {"id": 2,"org":"OB"}]}, {"profiles": [{"id": 3,"org":"OB"}, {"id": 4,"org":"OB"}]}]
this is what I try:
UPDATE
yewu
SET
data = (
SELECT
jsonb_agg((
SELECT
jsonb_set(oc, '{profiles}', jsonb_agg((
SELECT
jsonb_set(p, '{org}', yewu.org::jsonb)
FROM jsonb_array_elements(oc -> 'profiles') p)))))
FROM
jsonb_array_elements(data) oc)
RETURNING
id;
and error:
ERROR: aggregate function calls cannot be nested
LINE 8: jsonb_set(oc, '{profiles}', jsonb_agg((
^