Refactor HAVING and WHERE to share more code