You'll need to provide a bit more info.
Script it all out for us (Check, create, insert, query clean up) and show examples of the output you're wanting.
Check out the link in my signature.
For better, quicker answers on T-SQL questions, read Jeff Moden's suggestions.
"Million-to-one chances crop up nine times out of ten." ― Terry Pratchett, Mort