我有 json 类型的字段,像这样
数据
{"age": 44, "name": "Jun"}
{"age": 19, "name": "Pablo", "attempts": [11, 33, 20]}
{"age": 33, "name": "Maria", "attempts": [77, 10]}
这里有些 json 数据有“attempts”数组,有些则没有。当 json 有这个数组时,我需要得到不同字段中数组元素的总和,需要像这样的结果
数据,sum_of_array
{"age": 44, "name": "Jun"} , (nothing here)
{"age": 19, "name": "Pablo", "attempts": [11, 33, 20]} , 64
{"age": 33, "name": "Maria", "attempts": [77, 10]} , 87
最佳答案
SELECT attempts.id,
sum(vals.v::integer) sum_attempts
FROM attempts
LEFT JOIN LATERAL jsonb_array_elements_text(val->'attempts') vals(v)
ON TRUE
GROUP BY attempts.id;
如果您使用 json
而不是 jsonb
,请使用 json_array_elements_text
。
关于json - json数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43277178/