11

What I want to do is sum 29.0 and 34.65 and group by P_id

Table: transaction_items
Column name: Debits, P_id
Column data type: text, text

Data:


Debits

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

P_id

16
16

I tried using the solution mentioned here

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;

However, I got an error saying "cannot deconstruct a scalar".

Can someone please let me know how to parse the values I am looking for?

1
  • the link is useful, but did not show as a clickable link. I tried to edit this, and while editing the preview showed a clickable link, but not after saving the edit. Using Firefox. Feel free to reverse or improve my edit :-) Commented Jun 9, 2023 at 9:39

1 Answer 1

23

It seems that your data is broken. The values of Debits column are not valid json due to the lack of right square brackets. Assuming that your data should look like this:

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

the following query does what you want:

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.