Refactor Where and Having clauses