• Ok... now I'm sure.  If you run the code to generate the test table as we did above and then run the code below, you'll see what I mean.  Details are in the comments.


    --===== This is a single column pivot and it works just fine (for a PIVOT).
         -- It produces the expected 80 rows from a million.
     SELECT  Company
            ,YEAR
            ,Q1Amt = amt.[1]
            ,Q2Amt = amt.[2]
            ,Q3Amt = amt.[3]
            ,Q4Amt = amt.[4]
       FROM (SELECT Company,[Year],[Quarter],Amount FROM #SomeTable3) AS src
              PIVOT (SUM(Amount) FOR [Quarter] IN ([1],[2],[3],[4])
            ) amt
      ORDER BY Company, Year
    ;
    --===== This demonstrates that you can't have more in the src query than what the PIVOT will use
         -- which also means that you MUST have a source query for each column to be pivoted.
         -- All we did was add the Quantity column to the "src" aliased derived table and Pivot no
         -- longer works correctly.  Try it and see. And check out the row count.
    SELECT Company
            ,YEAR
            ,Q1Amt = amt.[1]
            ,Q2Amt = amt.[2]
            ,Q3Amt = amt.[3]
            ,Q4Amt = amt.[4]
       FROM (SELECT Company,[Year],[Quarter],Amount,Quantity FROM #SomeTable3) AS src
              PIVOT (SUM(Amount) FOR [Quarter] IN ([1],[2],[3],[4])
            ) amt
      ORDER BY Company, Year
    ;

    --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)