Add group by, refactor code