An earlier question covers how to use jOOQ's MULTISET_AGG feature to order a query based on an aggregate function over a nested collection: use GROUP BY to group the query by all the selected columns from the parent table, rather than trying to exploit implementation details of MULTISET.
Is there an approach that works with multi-level collections? I'm using PostgreSQL but obviously if there's an engine-independent way to do it, even better.
For example, if I have a nested query using MULTISET:
var results =
create
.select(
ORGANIZATIONS.ID,
ORGANIZATIONS.NAME,
multiset(
select(
DEPARTMENTS.ID,
DEPARTMENTS.NAME,
multiset(
select(EMPLOYEES.ID, EMPLOYEES.SALARY, EMPLOYEES.NAME)
.from(EMPLOYEES)
.where(EMPLOYEES.DEPARTMENT_ID.eq(DEPARTMENTS.ID)))))
.from(DEPARTMENTS)
.where(DEPARTMENTS.ORGANIZATION_ID.eq(ORGANIZATIONS.ID)))
.from(ORGANIZATIONS)
.fetch();
I can easily sort each department's employees by salary if I put an ORDER BY in the innermost query.
multiset(
select(EMPLOYEES.ID, EMPLOYEES.SALARY, EMPLOYEES.NAME)
.from(EMPLOYEES)
.where(EMPLOYEES.DEPARTMENT_ID.eq(DEPARTMENTS.ID))
.orderBy(EMPLOYEES.SALARY.desc()))))
But how do I also sort the list of departments by the highest employee salary, and the list of organizations by the highest employee salary across its departments?
Changing the MULTISETs into MULTISET_AGGs and only doing the ORDER BY on the top level of the query, as in the earlier question with just one level of nesting, seems like it can't work here because you'd need to group by two different sets of columns at the same time, and also because you can't nest aggregate functions (at least on PostgreSQL.)