在 PostgreSQL 聚合中连接 JSON 个数组

Concatenate JSON arrays in PostgreSQL aggregate

我有一个 table,其中包含 JSON 类型的字段,包含数据数组:

      Column       |  Type   
-------------------+---------
 id                | integer 
 user_id           | uuid    
 changes           | jsonb   
 exercise_entry_id | integer

changes 字段包含 JSON 个对象的列表。

对于数据清理任务,我需要将 changes 字段的内容连接为一个聚合,返回另一个非嵌套的 JSON 数组。

例如,数据库包含以下行:

id | user_id | changes         | exercise_entry_id
---+---------+-----------------+---------------------
 1 | foo     | ['a', 'b']      | 3
 2 | foo     | ['c', 'd']      | 3

我需要一个结果,按 user_id 和 exercise_entry_id 分组,其中更改按如下方式串联。

user_id | changes                     | exercise_entry_id
--------+-----------------------------+---------------------------
 foo    | ['a', 'b', 'c', 'd']        | 3

demo:db<>fiddle

SELECT
    user_id,
    jsonb_agg(elems) AS changes,
    exercise_entry_id
FROM
    mytable,
    jsonb_array_elements(changes) as elems
GROUP BY user_id, exercise_entry_id
  1. 使用 jsonb_array_elements()
  2. 将数组元素扩展为每个元素一行
  3. 使用 jsonb_agg()GROUP BY
  4. 将它们重新聚合到一个数组中