SQL Server - Converting row data to columns

  • I am working on a project where I have the below requirement

    My source table is

    PeriodID PeriodName ProductID ProductName Productvalue

    -------- ---------- --------- ----------- ------------

    10 Jan 100 A 15

    20 Feb 100 A 25

    30 Mar 100 A 35

    10 Jan 200 B 12

    20 Feb 200 B 14

    30 Mar 200 B 18

    10 Jan 300 C 22

    20 Feb 300 C 23

    30 Mar 300 C 38

    I want the output of the table to be like this

    Destination table

    PeriodID PeriodName A_ID A B_ID B C_ID C

    -------- ---------- ---- -- ---- -- ---- --

    10 Jan 100 15 200 12 300 22

    20 Feb 100 25 200 14 300 23

    30 Mar 100 35 200 18 300 38

    I am trying to use pivot and unpivot of sql server 2008, but I am not that familiar with the features of those operators. I know this requirement looks weird,but this is how I want my output result set.

    Please help me in this, I am really in trouble from past few days to get over this.

  • The following article has your answer both by method and with performance in mind.

    http://qa.sqlservercentral.com/articles/T-SQL/63681/

    --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)
    Intro to Tally Tables and Functions

Viewing 2 posts - 1 through 1 (of 1 total)

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