refactoring redundant subqueries into aggregate tables and simplifying summary table