Refactoring grouped_by sceanrios and adding a unit test