2017-08-30 94 views
1

我有survey_results表,有以下欄目:PostgreSQL的 - 分組通過jsonb列

id - integer 
score_labels - jsonb 

score_labels列數據格式如下:

{"total": "High", "risk": "High"}

現在我想有SQL查詢將通過此score_labels列對我的調查結果進行分組和統計。這是最後的結果應該是什麼樣子:

total       risk 
-------      ------ 
{high: 2, medium: 1, low: 0} {high: 1, medium: 2, low: 1} 

我想指望通過其得分標籤的調查結果。 PostgreSQL有辦法做到這一點嗎?

下面是簡單sqlfiddle與下面的模式:

http://sqlfiddle.com/#!17/0367f/1/0

回答

3

一個比較複雜的一種聚合:

with my_table (id, score_labels) as (
values 
(1, '{"total": "High", "risk": "High"}'::jsonb), 
(2, '{"total": "High", "risk": "Low"}'::jsonb), 
(3, '{"total": "Low", "risk": "Medium"}'::jsonb) 
) 

select 
    jsonb_build_object(
     'high', count(*) filter (where total = 'High'), 
     'medium', count(*) filter (where total = 'Medium'), 
     'low', count(*) filter (where total = 'Low') 
    ) as total, 
    jsonb_build_object(
     'high', count(*) filter (where risk = 'High'), 
     'medium', count(*) filter (where risk = 'Medium'), 
     'low', count(*) filter (where risk = 'Low') 
    ) as risk 
from (
    select 
     score_labels->>'total' as total, 
     score_labels->>'risk' as risk 
    from my_table 
    ) s 

       total    |    risk     
------------------------------------+------------------------------------ 
{"low": 1, "high": 2, "medium": 0} | {"low": 1, "high": 1, "medium": 1} 
(1 row)