I have a Table which contains data like id, country, city,capacity. Capacity is a JSON array field which has values like
[{‘totalCapacity’:100.0},{‘totalCapacity’:90.0},{‘totalCapacity’:80.0},{‘totalCapacity’:80.0}] against a row in table, so row in table looks like
id | country | city | capacity |
---|---|---|---|
1 | usa | new-york | [{‘totalCapacity’:100.0},{‘totalCapacity’:90.0},{‘totalCapacity’:80.0},{‘totalCapacity’:80.0}] |
Now I want result as
id | country | city | sum(capacity) |
---|---|---|---|
1 | usa | new-york | 350 |
i.e sum of totalCapacity against each row.
Tried this
SELECT
id,
country,
city,
SUM(JSON_VALUE(capacity, '$.totalCapacity')) AS total_capacity
FROM
A
GROUP BY
id,
country,
city;
but getting nulls in total_capacity
2
Answers
You can
CROSS JOIN LATERAL
aJSON_TABLE
and aggregate in that:Which, for the sample data:
Outputs:
fiddle
From 21, you can also use sum() item function directly in json_value: