Given a column with json objects, how to sum them based on the keys using sql?
{"A": 10, "B": -5}
{"A": 20}
{"A": -15, "B": -5}
{"A": -10, "C": 77}
Result:
{"A": 5, "B": -10, "C": 77}
Given a column with json objects, how to sum them based on the keys using sql?
{"A": 10, "B": -5}
{"A": 20}
{"A": -15, "B": -5}
{"A": -10, "C": 77}
Result:
{"A": 5, "B": -10, "C": 77}
2
Answers
Use
jsonb_each_text()
and the necessary casts for this:Working fiddle
You can first perform the summation via aggregation and then combine the results into a single JSON object with
jsonb_object_agg
:See fiddle