[英]Postgres sum of array stored in jsonb
I have a postgres database where some data are stored as jsonb arrays:我有一个 postgres 数据库,其中一些数据存储为 jsonb 数组:
id | start | duration | value
----+------------------------+--------------+------------
1 | 2019-01-04 18:34:00+01 | [60] | [7]
2 | 2019-01-04 18:44:00+01 | [60] | [9]
3 | 2019-01-04 19:00:00+01 | [60] | [6]
4 | 2019-01-04 19:06:00+01 | [60] | [17]
5 | 2019-01-04 19:19:00+01 | [60] | [9]
6 | 2019-01-04 19:41:00+01 | [60, 60, 60] | [13, 8, 9]
7 | 2019-01-04 19:46:00+01 | [60] | [7]
8 | 2019-01-04 19:49:00+01 | [60] | [0]
I would like to get the sum of all the values in the array in the 'value'-field.我想获得“值”字段中数组中所有值的总和。
I can get all the values from the arrays using jsonb_array_elements:我可以使用 jsonb_array_elements 从数组中获取所有值:
=# select jsonb_array_elements(value),value from step limit 20;
jsonb_array_elements | value
----------------------+------------
7 | [7]
9 | [9]
6 | [6]
17 | [17]
9 | [9]
13 | [13, 8, 9]
8 | [13, 8, 9]
9 | [13, 8, 9]
7 | [7]
and so on.等等。 So I thought
所以我认为
select sum(jsonb_array_elements(value)::integer),start from step group by start
would do it, but I am told: ERROR: aggregate function calls cannot contain set-returning function calls HINT: You might be able to move the set-returning function into a LATERAL FROM item.会这样做,但我被告知:错误:聚合函数调用不能包含设置返回函数调用提示:您可以将设置返回函数移动到 LATERAL FROM 项中。
I have been looking a little bit into LATERAL FROM, but I still don't really get what postgres wants me to do...我一直在研究 LATERAL FROM,但我仍然不明白 postgres 要我做什么......
Would it be easier to do this if I store the duration and value as arrays rather than json?如果我将持续时间和值存储为数组而不是 json,这样做会更容易吗?
Use the function in a lateral join:在横向连接中使用该函数:
select start, sum(number::int)
from step s
cross join jsonb_array_elements_text(value) as number
group by start
start | sum
------------------------+-----
2019-01-04 19:00:00+01 | 6
2019-01-04 19:46:00+01 | 7
2019-01-04 18:44:00+01 | 9
2019-01-04 19:19:00+01 | 9
2019-01-04 18:34:00+01 | 7
2019-01-04 19:06:00+01 | 17
2019-01-04 19:49:00+01 | 0
2019-01-04 19:41:00+01 | 30
(8 rows)
This cross join is a lateral join, the function is executed once for each row from step
.此交叉连接是横向连接,该函数对
step
每一行执行一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.