Using PIVOT or any other concept to transform row values to column values

  • Hi Everyone,

    I am in need of display results but stuck in middle.

    I have two results different ways.

    Result1

    col1 col2 col3 col4

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

    1 X M abc

    2 X M pqr

    Result2:

    col1 col2 col3 col4 col5 col6

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

    X M null null pqr null

    X M abc null null null

    From any one of the above results i have--and need to get result like

    Desired result:

    col1 col2 col3 col4 col5 col6

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

    X M abc null pqr null

    Please can anyone suggest any idea how to get desired result using PIVOT or any other??

    Remember the abc,pqr valued columns are varchar strings

    Thanks,

    Hemanth.

  • How do you know that abc belongs in col3 and pqr belongs in col5?


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • This looks easy enough to solve given a bit more information.

    Can you post the queries that gave the results above, and if you posted some sample data you would most likely get a solution straight away.

  • Based on what we've got so far, this could be what you want:

    --=======================================================

    -- Test data:

    --=======================================================

    drop table #temp;

    create table #temp

    (

    col1 int,

    col2 char(1),

    col3 char(1),

    col4 char(3)

    );

    insert #temp values ( 1, 'X', 'M', 'abc' );

    insert #temp values ( 2, 'X', 'M', 'pqr' );

    --=======================================================

    -- Solution:

    --=======================================================

    select

    col1=col2,

    col2=col3,

    col3=max(case when col1=1 then col4 else null end),

    col4=null,

    col5=max(case when col1=2 then col4 else null end),

    col6=null

    from #temp

    group by col2, col3;

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

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