【发布时间】: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
【问题讨论】:
-
这是我在 Python 中要做的,但在 Postgres 中需要它:stackoverflow.com/questions/5236296/…
标签: sql postgresql jsonb