Postgres 从聚合行创建 JSON 对象

alo*_*ras 5 sql postgresql

我在创建 JSON 对象时遇到了一些问题,其中对象的键是我在 Postgres 中聚合行的值。

这是我正在使用的表格:

create table if not exists safety_training_options (
  id serial primary key,
  option_type text not null,
  name text not null
)
Run Code Online (Sandbox Code Playgroud)

以及一些示例数据:

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');
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的查询,它将为我提供聚合行:

select 
    option_type as type,
    json_agg(sto.name) as options
from safety_training_options as sto
group by sto.option_type;
Run Code Online (Sandbox Code Playgroud)

结果集:

????????????????????????????????????????
?    type    ?         options         ?
????????????????????????????????????????
? method     ? ["Online", "Classroom"] ?
? frequency  ? ["Daily, "Weekly", ...] ?
? class_type ? [...]                   ?
? category   ? [...]                   ?
????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是如何构建一个 json 对象,其中键是类型列中的值,值是选项列中的数组。我希望我的最终结果如下所示:

{
    "method": [...],
    "category": [...],
    "frequency": [...],
    "class_type": [...]
}
Run Code Online (Sandbox Code Playgroud)

一个额外的问题是我可以重命名这些值以使它们复数吗?如果我可以使 json 对象中的键像“方法”“类别”“频率”和“class_types”这样的复数形式,那就太好了。我知道我可以将表中的值更改为复数,但我很好奇是否有另一种方法可以构建自定义 json 对象。

Mic*_*zzi 8

只需使用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
Run Code Online (Sandbox Code Playgroud)