我有一个像这样的数据集:
id | recipients_by_data
------------+------------------------------------------------------------
1000000001 | {"name": "users", "phone": "users"}
1000000002 | {"address": "users", "phone": "administrators"}
1000000003 | {"birthdate": "managers"}
1000000004 | {"name": "citizens", "phone": "citizens", "gender": "none"}
...
收件人为jsonb类型。
我想像这样将所有收件人值汇总到一个字段中:
id | data_recipients
------------+--------------------------------------------------------
1000000001 | users
1000000002 | users, administrators
1000000003 | managers
1000000004 | citizens, none
我该如何实现?
答案 0 :(得分:0)
不确定它是否是最佳选择,但这可以起作用:
WITH agg_recipients AS (
SELECT id, string_agg(value, ', ') FROM (
SELECT id, value
FROM applications, jsonb_each_text(recipients_by_data)
GROUP BY jsonb_each_text.value, id
) a
GROUP BY id
)
UPDATE applications
SET data_recipients = agg_recipients.string_agg
FROM agg_recipients
WHERE applications.id = agg_recipients.id;