`I'm trying to return the value of a subquery into a json_build_object, the subquery returns the right values but when the full select is ran the results are incorrect. It might be worthwhile noting that the full select is a left join of a view.
SELECT r.id, sum(q.total) AS overall_total,
jsonb_agg(json_build_object('count', q.total, 'type', der.name)) AS totals
FROM test.table_a p
JOIN test.table_b r
ON p.root_id = r.id
inner join (
select r.id, de.value_id as error_type, count(de.value_id) as total
from test.table_c de
inner join tests.error dr on de.value_id = dr.id
inner join test.table_a p on de.process = p.id
inner join test.table_b r on p.root = r.id
group by r.id, de.value_id
) q on q.id = r.id
inner join test.table_c er on er.process = p.id
inner join tests.error der on er.value_id = der.id
GROUP BY r.id) er on er.id = rs.id
The subquery returns -
Since I'm trying to count the number of occurrences for value_id based on ID, I believe I have gotten the right information.
Full query results and desired output -
I want to return the total errors for that given ID and an array of json objects, inside each object is the type (value_id text representation) and a count for how many of that type there is.
Currently the query is returning the wrong overall_total and it seems to be duplicating the types within the array. Where did I go wrong?

