我想要做的是总和29.0和34.65以及按P_id分组
表:transaction_items 列名:Debits,P_id 列数据类型:文本,文本 数据:
[{"amount":29.0,"description":"Fee_Type_1"}
[{"amount":"34.65","description":"Fee_Type_1"}
16
16
我尝试使用此处提到的解决方案[How to get elements from Json array in PostgreSQL
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;
然而,我得到一个错误说"无法解构标量"。
有人可以让我知道如何解析我想要的价值观吗?
谢谢。
答案 0 :(得分:2)
您的数据似乎已被破坏。由于缺少右方括号,Debtits
列的值无效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;