Query prepared for group by