簡體   English   中英

在PostgreSQL聚合中連接JSON數組

[英]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
  1. 使用jsonb_array_elements()數組元素擴展為每個元素一行
  2. 使用jsonb_agg()GROUP BY它們重新聚合為一個數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM