sql >> Database teknologi >  >> RDS >> PostgreSQL

PostgreSQL - gruppering efter jsonb-kolonne

En lidt kompliceret form for sammenlægning:

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) 



  1. hvordan man opretter mysql-skema i nodejs

  2. På Duplicate Key Update samme som indsæt

  3. Sådan sikkerhedskopieres gemte procedurer i MySQL

  4. PostgreSQL ufølsom SELECT på array