【问题标题】:Aggregate jsonb unique values in one field in postgres在 postgres 的一个字段中聚合 jsonb 唯一值
【发布时间】:2019-04-04 09:20:29
【问题描述】:

我有一个这样的数据集:

     id     |                       recipients_by_data                       
------------+------------------------------------------------------------
 1000000001 | {"name": "users", "phone": "users"}
 1000000002 | {"address": "users", "phone": "administrators"}
 1000000003 | {"birthdate": "managers"}
 1000000004 | {"name": "citizens", "phone": "citizens", "gender": "none"}
...

其中收件人是 jsonb 类型。

我想将所有收件人的值聚合到 on 字段中,如下所示:

     id     |                       data_recipients                       
------------+--------------------------------------------------------
 1000000001 | users
 1000000002 | users, administrators
 1000000003 | managers
 1000000004 | citizens, none

我怎样才能做到这一点?

【问题讨论】:

    标签: postgresql aggregate-functions jsonb


    【解决方案1】:

    不确定它是否是最佳的,但这是可行的:

    WITH agg_recipients AS (
      SELECT id, string_agg(value, ', ') FROM (
        SELECT id, value
        FROM applications, jsonb_each_text(recipients_by_data)
        GROUP BY jsonb_each_text.value, id
      ) a
      GROUP BY id
    )
    UPDATE applications
    SET data_recipients = agg_recipients.string_agg
    FROM agg_recipients
    WHERE applications.id = agg_recipients.id;
    

    【讨论】:

      猜你喜欢
      • 2020-12-07
      • 1970-01-01
      • 2021-11-03
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多