it's kind of looping within loop.. this kind of situation is tough to handle in SQL, it would be very simpler if you do it through code (provided that you have option)
Hemant Srivastava
Software Developer
MVP (C# Corner)http://hemant-srivastava.blogspot.com/Please mark this answer as
accepted answer if it resolves your problem.