我在attrs字段中有这样的json数据。我想要的金额为target_pencairan,但结果为0,有人可以帮忙吗?
"attrs": {
"tgl_mulai": "null",
"tgl_selesai": null,
"target_pencairan": [1000, 2000]
}`
select id,parent_id,level, SUM(attrs->>'$.target_pencairan') as target_pencairan
from project group by id
最佳答案
您可以使用json_extract
功能。
select id,
sum(json_extract(t1.attrs, concat('$.attrs.target_pencairan[', t2.col1, ']')))
from project t1
cross join (
select 0 as col1 union
select 1 union
select 2 union
select 3 union
select 4 union
select 5
) t2
group by id;
对于mysql v8.0,可以使用
json_table
函数。select id, parent_id, sum(res)
from project t1
cross join
json_table(t1.attrs,
"$.attrs.target_pencairan[*]"
columns(
`res` int path "$"
)
) t2
group by id, parent_id;
参见dbfiddle。