PostgreSQL - 按jsonb列分组

时间:2017-08-30 13:16:13

标签: sql postgresql jsonb

我有survey_results表,其中包含以下列:

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

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)