オブジェクトのキーがPostgresの行を集計する値であるJSONオブジェクトを作成する際に問題が発生します。Postgres集計行からJSONオブジェクトを作成する
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オブジェクトのキーを "メソッド" "カテゴリ" "頻度"や "class_types"のように複数にすることができれば嬉しいです。私はテーブルの値を複数に変更することができますが、カスタムjsonオブジェクトを作成する別の方法があるのか不思議です。