Did you consider using the :group by... operator for the grouping?