Given a table containing the following fields
| id | sign1 | value1 | qty1 | sign2 | value2 | qty2 |
|---|---|---|---|---|---|---|
| 1 | "positive" | "A" | 10 | "negative" | "B" | 5 |
How to create a SQL query that will generate a JSON object that will look like this?
{"A": 10, "B": -5}
>Solution :
A quick and dirty example:
create table json_object (id integer, sign1 varchar, value1 varchar, qty1 integer, sign2 varchar, value2 varchar, qty2 integer);
insert into json_object values (1, 'positive', 'A', 10, 'negative', 'B', 5);
select json_build_object(value1, qty1 * (case when sign1 = 'positive' then 1 else -1 end), value2, qty2 * (case when sign2 = 'positive' then 1 else -1 end)) from json_object;
json_build_object
----------------------
{"A" : 10, "B" : -5}