Unpivot Function

  • Hi Guys,

    Can any one please help me with this?

    I've this result from my 'case' query;

    Jan Feb Mar April

    1 2 3 4

    I want ;

    Month Value

    JAN 1

    Feb 2

    Mar 3

    April 4

    Thanks in advance,

    Saumil

  • Try this:

    declare @t table (Jan int, Feb int, Mar int, April int)

    insert @t

    (Jan, Feb, Mar, April)

    values

    (1, 2, 3, 4)

    select * from @t

    select [month], value

    from

    (select Jan, Feb, Mar, April from @t) t

    unpivot

    (value for [month] in (Jan, Feb, Mar, April)) u

    Don Simpson



    I'm not sure about Heisenberg.

  • saumil1987 (5/6/2015)


    Hi Guys,

    Can any one please help me with this?

    I've this result from my 'case' query;

    Jan Feb Mar April

    1 2 3 4

    I want ;

    Month Value

    JAN 1

    Feb 2

    Mar 3

    April 4

    Thanks in advance,

    Saumil

    I've always preferred to UNPIVOT using the CROSS APPLY VALUES approach:

    declare @t table (Jan int, Feb int, Mar int, April int)

    insert @t

    (Jan, Feb, Mar, April)

    values

    (1, 2, 3, 4);

    SELECT [Month], Value

    FROM @t a

    CROSS APPLY

    (

    VALUES('Jan', Jan),('Feb', Feb),('Mar', Mar),('April', April)

    ) b ([Month], Value);

    If you read the article about that in my signature, you'll understand why.


    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

  • Thanks Don,

    It worked. Appreciate your help.

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

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