This doesn't seem that complex but I can't know for sure because I know nothing of your tables and nothing of the data. As it is, my recommedation would be to "peel just one potato at a time" (divide'n'conquer) and the answer will reveal itself. Of course, you'd know what the tables and data look like.
My other recommendation is to take a look at the article at the first link in "Helpful Links" in my signature line below. Sometimes the process of prepping the question jars something loose and you come up with your own solution. If not, it does prepare your question to get better help, usually in the form of a tested code.
is pronounced ree-bar and is a Modenism for R
First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:
How to post code problemsHow to post performance problemsForum FAQs