[英]Concatenate JSON arrays in PostgreSQL aggregate
我有一個表,其中包含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
它們重新聚合為一個數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.