Please do not use attachments - a simple cut and paste (using the code tags) is sufficient and more efficient.
There is the same topic just a few below yours. was that not sufficient for you?
And there appears to be a sudden 'requirement' for this type of processing due to a competition. as it is a compettion then getting the answer from a forum is cheating. However, you should research CTEs (Common Table Expressions).