Fix bug where GROUP BY was applied when not needed