在 PostgreSQL 的 Json 行中总结一个值

Sum up a value in Json row inside PostgreSQL

假设我在 PostgreSQL 中有一个 table,它有两列,Id 和 Doc。 在 Doc 列中有一个 Json 对象,如下所示:

{"eid":{"a":5, "b":6, "c":9}, "time":12345}
{"eid":{"b":6, "c":9, "x":25}, "time":13255}

如果能帮我编写一个根据指定时间汇总 'a' 个 eid 的查询,我将不胜感激。 谢谢

我不确定你所说的 "according to specified time" 是什么意思,但我想你想要:

SELECT * FROM j;
┌───────────────────────────────────────────────────┐
│                        doc                        │
├───────────────────────────────────────────────────┤
│ {"eid": {"a": 5, "b": 6, "c": 9}, "time": 12345}  │
│ {"eid": {"b": 6, "c": 9, "x": 25}, "time": 13255} │
└───────────────────────────────────────────────────┘
(2 rows)

SELECT SUM((doc#>>'{eid,a}')::integer) 
FROM j 
WHERE (doc->>'time')::integer = 12345;
┌─────┐
│ sum │
├─────┤
│   5 │
└─────┘
(1 row)

编辑

一次获取所有键(您可能需要根据您的架构将 jsonb_* 更改为 json_*):

SELECT key, SUM(jsonb_extract_path_text(doc, 'eid', key)::integer)
FROM j, jsonb_object_keys(doc->'eid') sub(key)
GROUP BY key
;
┌─────┬─────┐
│ key │ sum │
├─────┼─────┤
│ x   │  25 │
│ b   │  12 │
│ a   │   5 │
│ c   │  18 │
└─────┴─────┘
(4 rows)

要对给定 time 的数组 eid 的所有值求和,请使用此查询:

select time, sum(value)
from (
    select
        (json_each(doc->'eid')).value::text::int,
        doc->>'time' as time
    from events 
    ) alias
group by 1
order by 1