I'm trying to find a way to do a restriction on a nested aggregation query
For example:
I want a report of CA & NV total students when the average class size is above 30.
SQL would be:
Code:
select schoolId, avgClassSize, totalStudents from (
select schoolId, avg(classSize) as avgClassSize, sum(classSize) as totalStudents
from classrooms where stateCode in ('CA", "NV') group by schoolId
) as agg
where agg.avgClassSize > 30 order by agg.totalStudents desc;
Where I might have a single table:
Code:
Classrooms{
String stateCode;
int schoolId;
int classSize;
}
My Java function would look something like this:
Code:
public List<SchoolReport> getSchoolReport(Session session, List<String> states) {
// The inner query
DetachedCriteria agg = DetachedCriteria.forClass(Classrooms.class);
// list the aggregation fields
ProjectionList projections = Projections.projectionList();
projections.add(Projections.groupProperty("schoolId").as("schoolId"));
projections.add(Projections.avg("classSize").as("avgClassSize"));
projections.add(Projections.sum("classSize").as("totalStudents"));
agg.setProjection(projections);
// restrict inner query to only desired states
agg.add(Restrictions.in("stateCode", states));
// The outter query
DetachedCriteria outter = DetachedCriteria.forClass(SchoolReport.class);
// Somehow reference the inner query
//??????????????????????????????
outter.add(MAGIC_HERE(agg));
//??????????????????????????????
// restrict the report to schools which have large class sizes
outter.add(Restrictions.gt("avgClassSize", 30));
// Show largest schools first
outter.addOrder(Order.desc("totalStudents"));
// do actual query
return (List<SchoolReport>)outter.getExecutableCriteria(session).list();
}
public static class SchoolReport{
int schoolId;
int totalStudents;
double avgClassSize;
}
What do I replace the MAGIC_HERE() function with? I can't get it with Subquiries.class examples that I've seen because the outter criteria isn't against another table. HQL is not desired as this is only an example of my real problem and I've already built classes that parse FilterSets building up complex ANDs & ORs restrictions that I don't want to have to redo in HQL if I don't have to.
Any help here would be appreciated.
Thanks,
Chris