I have a table test with two columns A and B and create table1 and table2 from it.
test table1 table2
A B A count(A) B count(B) A
95 1 95 7 1 3 95
5 11 5 2 11 2 5
95 1 9 4 95
95 9
95 1
95 9
5 11
95 9
95 9
How to get a result like:
{"node": [
{"child": [
{"value": 3,
"name": "1"},
{"value": 4,
"name": "9"}],
"value": 7,
"name": "95"},
{"child": [
{"value": 2,
"name": "11"}],
"value": 2,
"name": "5"}],
"name": "test",
"value": 9}
First I group by column A and count the groups name="95", value=7 and name="5", value=2. For each group I count also column B. There are alot of json functions, but till now I have no idea how to get the result above.
finely the query should be similar to:
select row_to_json(t) from ( select * , ( select array_to_json(array_agg(row_to_json(u))) from ( select * from table1 where table1.a=table2.a ) as u ) from table2 ) as t;