sql - 将字典列表转换为 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
解决方案
这可以使用jsonb_object_agg()
select profile_id, jsonb_object_agg(action_name, action_count)
from actions_table
group by profile_id;
推荐阅读
- c++ - 如何解决 cplex/c++ 的加权完成时间最小化问题?
- javascript - laravel ajax 意外结束 json 输入
- c++ - 在 AddressSanitizer 中止应用程序之前采取措施
- python - 如何将 .log 文件转换为 .csv 文件
- html - 出现在悬停图像上的文本应具有与图像不同的不透明度
- r - R 来自现有长字符串的新列 - 参考表,突变 case_when 不工作
- powerbi - 有没有办法比较行并根据列替换值?
- sql - SQL Server Integration Services:如何管理多个源?
- javascript - 验证 mat-date 选择器和 mat-time-picker
- mysql - MySQL 组与现有列一样