我有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
答案 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