簡體   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