Grouping query optimization