Refactor complex query