在postgres中将jsonb转换为常规数组
Converting jsonb to regular array in postgres
我有以下 table:
"Id"| "Data"
====+================================================
1 | { "emp": [
| {"id": "a1", "otherdata": "other"},
| {"id": "a2", "otherdata": "other"}
| ]
| }
----+------------------------------------------------
2 | { "emp": [
| {"id": "b1", "otherdata": "other"},
| {"id": "b2", "otherdata": "other"}
| ]
| }
-----------------------------------------------------
其中 "Data" 是 jsonb。
我需要创建一个临时 table 这种类型:
"Id"| "Emp"
====+=============
1 | {"a1", "a2"}
----+-------------
2 | {"b1", "b2"}
我该怎么做?
使用 jsonb_to_recordset
将数组值提取到行中,将它们分组,然后使用 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;
我有以下 table:
"Id"| "Data"
====+================================================
1 | { "emp": [
| {"id": "a1", "otherdata": "other"},
| {"id": "a2", "otherdata": "other"}
| ]
| }
----+------------------------------------------------
2 | { "emp": [
| {"id": "b1", "otherdata": "other"},
| {"id": "b2", "otherdata": "other"}
| ]
| }
-----------------------------------------------------
其中 "Data" 是 jsonb。
我需要创建一个临时 table 这种类型:
"Id"| "Emp"
====+=============
1 | {"a1", "a2"}
----+-------------
2 | {"b1", "b2"}
我该怎么做?
使用 jsonb_to_recordset
将数组值提取到行中,将它们分组,然后使用 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;