dynamic subqueries - added joins and sum