将字典列表转换为 Postgres jsonb 中的字典
Convert list of dictionaries into dictionary in 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
如何从这里获得我想要的结果(将字典列表转换为字典),或者如何修复我的原始查询?
注意事项
- 我需要一个笼统的答案,我可能有 > 10 个 action_names。
- 我想避免文本替换,例如
concat('{',replace(replace(replace(replace(jsonb_agg(jsonb_build_object(action_name, action_count)))::text, '[', ''), ']', ''), '{', '' ), '}', ''), '}')::jsonb
好的,现在我们已经掌握了所有信息,您可以这样做:
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
这可以使用 jsonb_object_agg()
来完成
select profile_id, jsonb_object_agg(action_name, action_count)
from actions_table
group by profile_id;
我有一个 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_names。
- 我想避免文本替换,例如
concat('{',replace(replace(replace(replace(jsonb_agg(jsonb_build_object(action_name, action_count)))::text, '[', ''), ']', ''), '{', '' ), '}', ''), '}')::jsonb
好的,现在我们已经掌握了所有信息,您可以这样做:
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
这可以使用 jsonb_object_agg()
select profile_id, jsonb_object_agg(action_name, action_count)
from actions_table
group by profile_id;