简体   繁体   中英

Perform group by on jsonb object using a json path

I have a jsonb object in Postgres column named metrics with following structure:

{"http": {"GET": {"statusCode": {"200": {"count": 100}, "500": {"count": 322}}}}}

I want to get total count by different httpmethod , statusCode so that I can plot it using Grafana. Can someone point me how can I use group by. Expected result should be:

httpMethod statusCode sum(count)
GET        200        100
GET        500        322

Assuming the structure is constant, and counts are integer values:

SELECT h.key AS http_method
     , s.key AS status_code
     , sum((s.value->>'count')::int) AS sum_count
FROM   tbl t
     , jsonb_each(t.js->'http') h
     , jsonb_each(h.value->'statusCode') s
GROUP  BY h.key, s.key;

db<>fiddle here

jsonb_each() in an implicit CROSS JOIN LATERAL join is the key ingredient.

About LATERAL :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM