在 PostgreSQL 聚合中连接 JSON 数组

Dav*_*ogt 10 sql postgresql json aggregate jsonb

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

      Column       |  Type   
-------------------+---------
 id                | integer 
 user_id           | uuid    
 changes           | jsonb   
 exercise_entry_id | integer
Run Code Online (Sandbox Code Playgroud)

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

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

假设数据库包含以下行:

id | user_id | changes         | exercise_entry_id
---+---------+-----------------+---------------------
 1 | foo     | ['a', 'b']      | 3
 2 | foo     | ['c', 'd']      | 3
Run Code Online (Sandbox Code Playgroud)

我需要一个结果,按 user_id 和 Exercise_entry_id 分组,其中更改按如下方式连接。

user_id | changes                     | exercise_entry_id
--------+-----------------------------+---------------------------
 foo    | ['a', 'b', 'c', 'd']        | 3
Run Code Online (Sandbox Code Playgroud)

S-M*_*Man 13

演示:数据库<>小提琴

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
Run Code Online (Sandbox Code Playgroud)
  1. 将数组元素扩展为每个元素的一行 jsonb_array_elements()
  2. 使用jsonb_agg()和将它们重新聚合为一个数组GROUP BY