我有json类型字段,如下所示
数据

{"age": 44, "name": "Jun"}

{"age": 19, "name": "Pablo", "attempts": [11, 33, 20]}

{"age": 33, "name": "Maria", "attempts": [77, 10]}

这里有些json数据有“尝试”数组,有些没有。当json有这个数组时,我需要得到不同字段中数组元素的和,需要如下结果
数据,数组的和
{"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_array_elements_text而不是json,请使用jsonb

关于json - json数组的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43277178/

10-11 04:24