Attempt to improve group by logic