It's not really clear what your question is. You are posting some code. What does that code do?
In any case, why do you want to use SQL for this? You have some data which you seem to want to present in some format. That format is often best achieved in the presentation layer. Several reporting components have built-in pivoting capabilities.
If you really want to do this in SQL, I have written how to do dynamic pivots here: http://www.sommarskog.se/dynamic_sql.html#pivot.
If you want someone to write a query for you, you should post CREATE TABLE statements for your table(s) and INSERT statements with sample data, enough to illustrate all angles of the problem, together with the expected result. Then we can copy and paste into a query window to develop a tested solution.
But chances are good that you should not use SQL at all for this.