如何在PostgreSQL中提取JSON数组元素

10
我想做的是将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"}

产品编号

16
16

我尝试使用这里提到的解决方案。
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;

然而,我遇到了一个错误,显示“无法解构标量”。
请问有人可以告诉我如何解析我正在寻找的值吗?

这个链接很有用,但没有显示为可点击的链接。我尝试编辑它,在编辑预览中可以点击链接,但保存编辑后却不能点击。我使用的是Firefox浏览器。请随意撤销或改进我的编辑 :-) - Roland
1个回答

22

看起来你的数据出现了问题。由于缺乏右方括号,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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接