在 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
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
- 使用
jsonb_array_elements()
将数组元素扩展为每个元素一行
- 使用
jsonb_agg()
和 GROUP BY
将它们重新聚合到一个数组中
我有一个 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
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
- 使用
jsonb_array_elements()
将数组元素扩展为每个元素一行
- 使用
jsonb_agg()
和GROUP BY
将它们重新聚合到一个数组中