Like the title of the question suggests, I'm attempting take a number of arbitrary sub-queries and combine them into a single, large query.
Ideally, I'd like to the data to be returned as a single record, with each column being the result of one of the sub-queries. E.G.
| sub-query 1 | sub-query 2 | ...
|-----------------|-----------------|-----------------
| (array of rows) | (array of rows) | ...
The sub-queries themselves are built using Knex.js in a Node app and are completely arbitrary. I've come fairly close to a proper solution, but I've hit a snag.
My current implementation has the final query like so:
SELECT
array_agg(sub0.*) as s0,
array_agg(sub1.*) as s1,
...
FROM
(...) as sub0,
(...) as sub1,
...
;
Which mostly works, but causes huge numbers of duplicates in the output. During my testing, I found that it returns records such each record is duplicated a number of times equal to how many records would have been returned without the duplicates. For example, a sub-query that should return 10 records would, instead, return 100 (each record being duplicated 10 times).
I've yet to figure out why this occurs or how to fix the query to not get the issue.
So far, I've only been able to determine that:
- The number of records returned by the sub-queries is correct when queried separately
- The duplicates are not caused by intersections between the sub-queries
- i.e. sub-queries contain rows that exist in other sub-queries
Thanks in advance.