我在创建 JSON 对象时遇到了一些问题,其中对象的键是我在 Postgres 中聚合行所依据的值。
这是我正在使用的表格:
create table if not exists safety_training_options (
id serial primary key,
option_type text not null,
name text not null
)
和一些示例数据:
insert into safety_training_options (option_type, name)
values ('category', 'General Industry'),
('category', 'Maritime'),
('category', 'Construction'),
('frequency', 'Daily'),
('frequency', 'Weekly'),
('frequency', 'Bi-weekly'),
('method', 'Online'),
('method', 'Classroom');
到目前为止,这是我的查询,它将为我提供聚合行:
select
option_type as type,
json_agg(sto.name) as options
from safety_training_options as sto
group by sto.option_type;
结果集:
╔════════════╦═════════════════════════╗
║ type ║ options ║
╠════════════╬═════════════════════════╣
║ method ║ ["Online", "Classroom"] ║
║ frequency ║ ["Daily, "Weekly", ...] ║
║ class_type ║ [...] ║
║ category ║ [...] ║
╚════════════╩═════════════════════════╝
我卡住的地方是如何构建一个 json 对象,其中键是类型列中的值,值是选项列中的数组。我希望最终结果如下所示:
{
"method": [...],
"category": [...],
"frequency": [...],
"class_type": [...]
}
一个额外的问题是我可以重命名这些值以使它们复数吗?如果我可以使 json 对象中的键复数,如“方法”、“类别”、“频率”和“类类型”,那就太好了。我知道我可以将表中的值更改为复数,但我很好奇是否有另一种方法可以构建自定义 json 对象。
最佳答案
只需使用 json_object_agg :
WITH tmp AS (
SELECT
option_type,
json_agg(sto.name) as training_options
FROM
safety_training_options as sto
GROUP BY
sto.option_type
)
SELECT json_object_agg(option_type, training_options) FROM tmp
关于sql - Postgres 从聚合行创建 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165059/