2017-11-07 9 views
2

オブジェクトのキーが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オブジェクトを作成する別の方法があるのか​​不思議です。

答えて

2

だけ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 
1

条件array_aggrow_to_jsonを考えてみましょう:

SELECT row_to_json(r) as output 
FROM 
( 
    (SELECT array_remove(array_agg(CASE WHEN s.option_type = 'category' 
             THEN s.name ELSE NULL END), NULL) AS category, 
      array_remove(array_agg(CASE WHEN s.option_type = 'frequency' 
             THEN s.name ELSE NULL END), NULL) AS frequency, 
      array_remove(array_agg(CASE WHEN s.option_type = 'method' 
             THEN s.name ELSE NULL END), NULL) AS method 
    FROM safety_training_options s 
    )  
) r; 

-- {"category":["General Industry","Maritime","Construction"], 
-- "frequency":["Daily","Weekly","Bi-weekly"], 
-- "method":["Online","Classroom"]} 

Rextester Demo

関連する問題