0

I have the following PostgreSQL table:

CREATE TABLE orders
(
    id uuid NOT NULL,
    order_date timestamp without time zone,
    data jsonb
);

Where data contains json documents like this:

{
    "screws": [
        {
            "qty": 1000,
            "value": "Wood screw"
        },
        {
            "qty": 500,
            "value": "Drywall screw"
        },
        {
            "qty": 500,
            "value": Concrete screw"
        }
    ],
    "nails": [
        {
            "qty": 1000,
            "value": "Round Nails"
        }
    ]
}

How do I can get an overall quantity for all types of screws across all orders? Something like this :)

select value, sum(qty) from orders where section = 'screws' group by value;

1 Answer 1

1

I am not quite sure why you are trying to sum up the qty values, because the GROUP BY value makes only sense if there would be several times the same value which can be summed, e.g. if you would have twice the value Wood screw.

Nevertheless, this would be the query:

step-by-step demo:db<>fiddle

SELECT
    elems ->> 'value' AS value,
    SUM((elems ->> 'qty')::int) AS qty
FROM
    orders,
    jsonb_array_elements(data -> 'screws') elems
GROUP BY 1
  1. Expand the screw array into one row per array element by jsonb_array_elements()
  2. Get the qty value by the ->> operator (which gives out a text type) and cast this into type int
  3. If really necessary, aggregate these key/value pairs.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.