So there are these 2 tables I want to group together by age so that i can find the total number of people from that age group from both the tables so far i'm able to achieve it but the way i want the JSON data to be is wrong
This is my approach:
SELECT temp.age, sum(temp.total), json_agg(temp.data_recs) as data_recs FROM (
SELECT
'31-40' as age, COUNT(*) as total,
json_agg(
CASE
WHEN table_1.age BETWEEN 31 AND 40
THEN json_build_object(
'country', table_1.country,
'Name', table_1.name
)
ELSE json_build_object(
'country', '',
'Name', ''
)
END
) AS data_recs
from table_1
WHERE table_1.age BETWEEN 31 AND 40
UNION ALL
SELECT
'31-40' as age, COUNT(*) as total,
json_agg(
CASE
WHEN table_2.age BETWEEN 31 AND 40
THEN json_build_object(
'country', table_2.country,
'Name', table_2.name
)
ELSE json_build_object(
'country', '',
'Name', ''
)
END
) AS data_recs
from table_2
WHERE table_2.age BETWEEN 31 AND 40
) AS temp group by temp.age
result from 1'st table eg.
age | total | data_recs
'31-40'| 2 | [{"name":"John","country":"USA"},{"name":"Eddy","country":"USA"}]
result from 2'nd table eg.
age | total | data_recs
'31-40'| 2 | [{"name":"Cienna","country":"Italy"},{"name":"Rosie","country":"Italy"}]
So far I'm able to achieve
age | total | data_recs
'31-40'| 4 | [[{"name":"John","country":"USA"},{"name":"Eddy","country":"USA"}],[{"name":"Cienna","country":"Italy"},{"name":"Rosie","country":"Italy"}]]
JSON array 1 = [{"name":"John","country":"USA"},{"name":"Eddy","country":"USA"}]
JSON array 2 = [{"name":"Cienna","country":"Italy"},{"name":"Rosie","country":"Italy"}]
What I want is :-
age | total | data_recs
'31-40' | 4 | [{"name":"John","country":"USA"},{"name":"Eddy","country":"USA"},{"name":"Cienna","country":"Italy"},{"name":"Rosie","country":"Italy"}]
comibined JSON what i want Should be like this:
[{"name":"John","country":"USA"},{"name":"Eddy","country":"USA"},{"name":"Cienna","country":"Italy"},{"name":"Rosie","country":"Italy"}]
Is there a way to do this or any other approach?