在postgres中将jsonb转换为常规数组

时间:2018-11-26 09:06:40

标签: sql postgresql jsonb

我有下表:

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

其中“数据”为jsonb。

我需要创建这种类型的临时表:

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用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;

请参见SQL Fiddle