This is a somewhat ambiguous request. Can you explain what the @NewID, @GroupID, and @i variables are for. We're those something you were attempting to use to solve this problem?
"I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."-- Itzik Ben-Gan 2001