Minor refactoring for building queries from aggregation tables.