PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

PostgreSQL - pengelompokan berdasarkan kolom jsonb

Jenis agregasi yang agak rumit:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Meningkatkan PostgreSQL 11 ke PostgreSQL 12 dengan Zero Downtime

  2. fungsi mengembalikan beberapa kolom sebagai satu kolom, bukan beberapa kolom

  3. Kloning SQL dan konversi kolom tanggal

  4. Menerapkan Postgres Sql di Apache Airflow

  5. PostgreSQL melalui SSH Tunnel