refactor complex queries for team details