PostgreSQL - grouping by jsonb column

牧云@^-^@ 提交于 2019-12-13 02:38:47

问题


I have survey_results table which has following columns:

id - integer
score_labels - jsonb

score_labels column data format looks like this:

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

Now I want to have sql query that will group and count my survey results by this score_labels column. This is what the final result should look like:

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

I want to count survey results by its score labels. Is there way to do it in PostgreSQL?

Here is simple sqlfiddle with the following schema:

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


回答1:


A somewhat complicated kind of aggregation:

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) 


来源:https://stackoverflow.com/questions/45961525/postgresql-grouping-by-jsonb-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!