我有一个 json 列,其中的条目如下所示:
{
"pages": "64",
"stats": {
"1": { "200": "55", "400": "4" },
"2": { "200": "1" },
"3": { "200": "1", "404": "13" },
}
}
“统计数据”是包含 http 状态代码与计数的集合(各种大小)。
我想将统计数据汇总到两个计算列中 - 一个用于 200
响应的总数,另一个用于响应总数(包括 200
) ).
最佳答案
您可以使用两个横向连接来取消嵌套内部对象,然后进行条件聚合:
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)
no_responses | no_200_responses -----------: | ---------------: 74 | 57
关于json - 在 PostgreSQL 中聚合 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62048887/