Added HAVING clause to compileQuery
Optimized getItems SQL