This is not a very clear description of what you are trying to do. Can you post some DDL, consumable sample data and an example of the expected results?
"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