refactored group by method