我想做的是将 29.0 和 34.65 相加并按 P_id 分组
Table: transaction_items
Column name: Debits, P_id
Column data type: text, text
数据:
借记
[{"amount":29.0,"description":"Fee_Type_1"}
[{"amount":"34.65","description":"Fee_Type_1"}
P_id
16
16
我尝试使用此处提到的解决方案 [https://stackoverflow.com/questions/27834482/how-to-get-elements-from-json-array-in-postgresql][1]
select transaction_line_items.P_id,
each_attribute ->> 'amount' Rev
from transaction_line_items
cross join json_array_elements(to_json(Debits)) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where (each_attribute -> 'amount') is not null;
但是,我收到一条错误消息“无法解构标量”。
有人可以告诉我如何解析我正在寻找的值吗?
谢谢。
最佳答案
看来你的数据坏了。由于缺少右方括号,Debits
列的值不是有效的 json。假设您的数据应如下所示:
[{"amount":29.0,"description":"Fee_Type_1"}]
[{"amount":"34.65","description":"Fee_Type_1"}]
下面的查询做你想做的:
select p_id, sum(amount)
from (
select p_id, (elements->>'amount')::numeric amount
from transaction_items
cross join json_array_elements(debits::json) elements
) sub
group by p_id;
关于arrays - 如何在postgresql中提取json数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887188/