I just discovered the json capabilities of postgresql but have trouble understanding how to generate json with queries. I hope the question I am asking makes sense and please excuse me if I am missing something obvious.
my problem ? how to generate json with some values being keys to others. here an example
drop table if exists my_table;
create table my_table(id int, sale_year int, sale_qty int);
insert into my_table values (10, 2007, 2);
insert into my_table values (10, 2008, 1);
insert into my_table values (10, 2009, 0);
insert into my_table values (20, 2009, 2);
insert into my_table values (30, 2011, 1);
insert into my_table values (30, 2012, 3);
The following statement
SELECT id, json_agg(to_json(my_table)) FROM public.my_table group by id;
gives me a json per id (e.g. for id = 20)
20, [{"id":20, "sale_year": 2009, "sale_qty": 2}]
my question is:
is it possible to return a json with the following structure ?
{"2009": 2}