3

I have a table inventory with a value column that contains JSON strings, with the following data structure:

{
 "category": {
 "item": ["price", "quantity"]
 },
 "widgets": {
 "foo": [300, 15]
 "bar": [500, 5],
 "baz": [400, 10]
 },
 ...
}

To query for a particular item, I use the following parameterized SQL:

SELECT
 (value::JSON->1ドル->2ドル->>0)::INT AS price
, (value::JSON->1ドル->2ドル->>1)::INT AS quantity
FROM inventory
WHERE as_of_date = 3ドル::DATE

...where 1ドル is the category, 2ドル is the item and 3ドル is the date.

Now I need to sum() all of the prices and quantities for each item in a category, and I'm not sure how to go about it. I've tried using JSON functions like json_each, but can't manage to get the nth array element from all JSON field values.

Evan Carroll
65.7k50 gold badges259 silver badges511 bronze badges
asked Apr 25, 2016 at 21:42

1 Answer 1

3

You can use json_each and LEFT JOIN LATERAL for this purpose:

WITH inventory AS (
 SELECT '{
 "category": {
 "item": ["price", "quantity"]
 },
 "widgets": {
 "foo": [300, 15],
 "bar": [500, 5],
 "baz": [400, 10]
 }
}'::text AS value
 )
SELECT
 v.key,
 (v.value->>0)::INT AS price
, (v.value->>1)::INT AS quantity
FROM inventory i
LEFT JOIN LATERAL json_each(i.value::JSON->1ドル) v ON (true)
WHERE as_of_date = 3ドル::DATE;

You can then filter, group by and sum as you need.

answered Apr 26, 2016 at 1:47
1
  • 1
    If I could up-vote this ten times I would. Nicely done! Commented Apr 26, 2016 at 14:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.