Pivot type query

  • Hey all,

    I need help trying to create a "pivot table" of sorts.

    I have a table named Players. Looks like this:

    PlayersIDDescription
    1Team
    2FirstName
    3LastName
    4Position
    5Hand

    I have been able to take that table and dynamically create a table named PlayersPivot.  It looks like this:

    TeamFirstNameLastNamePositionHand

    I have another table named Information.  Looks Like this:

    InformationIDPlayersIDMappingIDDescription
    111BlueJays
    221Frank
    331Thomas
    441DH
    551R
    612BlueJays
    722Roy
    832Halliday
    942Pitcher
    1052R
    1113BlueJays
    1223A.J.
    1333Burnett
    1443Pitcher
    1553R

    Here is my dilema.  Each distinct MappingID forms one "row" that I need to insert into the PlayersPivot table.  How can I "pivot" the data in Description field, by MappingID, into the appropriate columns.  The PlayersID corresponds to the PlayersID in the Players table.

    Any help would be greatly appreciated.

    Thanks in advance,

    Steve

  • Try the following link...you may have to search for follow-up articles as there were some revisions/bug fixes to this code.

    http://www.sqlteam.com/item.asp?ItemID=2955

     

  • Thanks Andrew for the link, however, after a few coffees, and some quiet, I was able to do it with a nested cursor.  I know, avoid at all costs, but in this case I couldnt figure how else to do it.

    Thanks,

    Steve

  • If the Players table does not change much, you may want to hard code like:

    SELECT MAX(CASE PlayersID WHEN 1 THEN [Description] END) AS Team

        ,MAX(CASE PlayersID WHEN 2 THEN [Description] END) AS FirstName

        ,MAX(CASE PlayersID WHEN 3 THEN [Description] END) AS LastName

        ,MAX(CASE PlayersID WHEN 4 THEN [Description] END) AS Position

        ,MAX(CASE PlayersID WHEN 5 THEN [Description] END) AS Hand

    FROM Information

    GROUP BY MappingID

     

  • That was attempt number one actually, util I was told that each "Teams" data may be different.  Once I tried a different team, no dice.

    The dynamic sql and cursor did solve the problem...now its battling the run time next.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply