• Truth be known, you've already done the hard part in the form of rows 21 through 42. I'm on my way to work so can't respond with code just now but forget any row that has a NULL fk and use the method in the following article to dynamically pivot the data the way you want. Considering the distribution of data, you might be able to skip the part where the Tally Table is used (you'll understand that statement once you get into the article).

    http://www.sqlservercentral.com/articles/Crosstab/65048/

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    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.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)