Refactor complex queries for team details

Helps #815