首页 > 解决方案 > 将字典列表转换为 Postgres jsonb 中的字典

问题描述

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

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

注意事项

标签: sqlpostgresqljsonb

解决方案


这可以使用jsonb_object_agg()

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

在线示例


推荐阅读