I am trying to get a sum of values in a JSON array grouped by a shop_id and key, and get the output in the same format.
So, with an array like this:
[
{
sales: {"bicycle": 2, "skateboard": 5},
shop_id: 6321
},
{
sales: {"bicycle": 1, "skateboard": 3},
shop_id: 6243
},
{
sales: {"bicycle": 3, "skateboard": 4},
shop_id: 6243
}
]
The output should look like:
[
{
sales: {"bicycle": 2, "skateboard": 5},
shop_id: 6321
},
{
sales: {"bicycle": 4, "skateboard": 7},
shop_id: 6243
}
]
The JSON input will always be uniform. I can get it to work if I use JSON_BUILD_OBJECT and JSON_AGG but I don't want to specify what keys to use while building JSON because the real data will probably hold around 20 different keys, so I am looking for a cleaner solution.
SELECT JSON_BUILD_OBJECT('bicycle', SUM((sales::json ->> 'bicycle')::int),
'skateboard', SUM((sales::json ->> 'skateboard')::int)
) AS sales,
shop_id
FROM (SELECT val ->> 'sales' AS sales, val ->> 'shop_id' AS shop_id
FROM (SELECT UNNEST($1)::jsonb AS val) core) outercore
GROUP BY shop_id;
How can I achieve something like this?