【问题标题】:Convert list of dictionaries into dictionary in Postgres jsonb将字典列表转换为 Postgres jsonb 中的字典
【发布时间】:2021-08-28 06:24:48
【问题描述】:

我有一个actions_table,看起来像:

profile_id | action_name | action_count
1          | action1     | 2
1          | action2     | 5
2          | action1     | 3
2          | action2     | 6
2          | action3     | 7
3          | action1     | 1

我想通过 profile_id 和 jsonify 聚合为:

profile_id | actions_count
1          | {"action1": 2, "action2": 5}
2          | {"action1": 3, "action2": 6, "action3": 7}
3          | {"action1": 1}

我能到达的最接近的是:

profile_id | actions_count
1          | [{"action1": 2}, {"action2": 5}]
2          | [{"action1": 3}, {"action2": 6}, {"action3": 7}]
3          | [{"action1": 1}]

通过查询:

select profile_id,
jsonb_agg(jsonb_build_object(action_name, action_count)) as "actions_count"
from actions_table
group by profile_id
order by profile_id

如何从这里获得我想要的结果(将字典列表转换为字典),或者如何修复我的原始查询?

注意事项

  • 我需要一个通用答案,我可能有超过 10 个 action_name。
  • 我想避免文本替换,例如concat('{',replace(replace(replace(replace(jsonb_agg(jsonb_build_object(action_name, action_count)))::text, '[', ''), ']', ''), '{', '' ), '}', ''), '}')::jsonb

【问题讨论】:

标签: sql postgresql jsonb


【解决方案1】:

这可以使用jsonb_object_agg()来完成

select profile_id, jsonb_object_agg(action_name, action_count)
from actions_table
group by profile_id;

Online example

【讨论】:

    【解决方案2】:

    好的,现在我们已经掌握了所有信息,您可以这样做:

    with p as (select distinct profile_id from actions_table)
    select p.profile_id,json_object(array_agg(action_name),array_agg(action_count::varchar)) 
    from p,actions_table
    where p.profile_id = actions_table.profile_id
    group by p.profile_id
    

    【讨论】:

    • 我需要一个通用且动态的答案,我可能有 > 10 种类型的操作作为键。我知道如何静态生成字典。
    • 首先这个查询json_agg(jsonb_build_object(key, value))返回[{"action1_count": 13}, {"action2_count": 39}]而不是[{action1_count: 13}, {action2_count: 39}]。在 json 中,键用双引号括起来。如果你想要一个正确的答案,问一个好问题。如果您的操作是从表格中检索的,您必须提供表格和数据的描述,否则您将无法获得答案。
    • 感谢您指出缺少的引号。
    • 更新问题。
    • OKKK,太棒了。很抱歉最初发布了一个不完整的问题。谢谢菲利普:)
    猜你喜欢
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多