繁体   English   中英

如何在postgresql中提取json数组元素

[英]How to extract json array elements in postgresql

我想要做的是求和 29.0 和 34.65 并按 P_id 分组

表:transaction_items 列名:Debits、P_id 列数据类型:text、text 数据:


借记

[{"amount":29.0,"description":"Fee_Type_1"}
[{"amount":"34.65","description":"Fee_Type_1"}

P_id

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;

但是,我收到一条错误消息,提示“无法解构标量”。

有人可以让我知道如何解析我正在寻找的值吗?

谢谢你。

看来您的数据已损坏。 由于缺少右方括号, 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM