Refactored a complex query.