简体   繁体   English

在 PostgreSQL 中聚合 JSON

[英]Aggregate JSON in PostgreSQL

I have a json column with entries that look like this:我有一个 json 列,其条目如下所示:

{
  "pages": "64",
  "stats": {
    "1": { "200": "55", "400": "4" },
    "2": { "200": "1" },
    "3": { "200": "1", "404": "13" },
  }
}

The 'stats' are collections (of various sizes) containing http status codes versus counts. “统计”是 collections(各种大小),包含 http 状态代码与计数。

I would like to aggregate the stats into two calculated columns - one for the total number of 200 responses and the other for the total number of responses (including 200 s).我想将统计信息汇总到两个计算列中 - 一个用于200响应的总数,另一个用于响应的总数(包括200 )。

You can use two lateral joins to unnest the inner objects, then do conditional aggregation:您可以使用两个横向连接来取消嵌套内部对象,然后进行条件聚合:

select 
    sum(z.cnt::int) no_responses,
    sum(z.cnt::int) filter(where z.code::int = 200) no_200_responses
from mytable t
cross join lateral jsonb_each(t.data -> 'stats') as x(kx, obj)
cross join lateral jsonb_each_text(x.obj) as z(code, cnt)

Demo on DB Fiddle : DB Fiddle 上的演示

no_responses | no_200_responses
-----------: | ---------------:
          74 |               57

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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