json数组的总和

时间:2017-04-07 11:38:17

标签: json postgresql

我有json类型字段,类似这样

数据

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

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

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

这里有一些json数据有"尝试"数组,有些不是。当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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

如果您的表格中有唯一的id标识列

,则此方法有效
SELECT your_table.*, tt.sum FROM your_table
LEFT JOIN (
    select id, SUM(arrvals) as sum FROM (
        select id, json_array_elements_text(CAST(your_json_column->>'attempts' AS json))::NUMERIC as arrvals  from your_table
    )t 
     group by id
) tt
ON your_table.id = tt.id