how to do pivot

  • Hi Guys,

    actually my table data looks

    Key value

    firstname surya

    firstname rakhi

    firstname venkat

    firstname shankar

    firstname dany

    I want to disply like

    firstname

    surya

    rakhi

    venkat

    shankar

    dany

    i write the below query

    SELECT firstname

    FROM test pvt

    PIVOT (MAX(pvt.value ) FOR pvt.key1 IN (firstname)) AS P

    but it showing

    firstname

    venkat

    Please help to solve this

  • Hi,

    I haven't used PIVOT because this can be solved with a CASE statement.

    DECLARE @table TABLE

    (

    [Key] VARCHAR(50),

    Value VARCHAR(50)

    )

    INSERT INTO @table

    SELECT 'firstname', 'surya'

    UNION ALL SELECT 'firstname', 'rakhi'

    UNION ALL SELECT 'firstname', 'venkat'

    UNION ALL SELECT 'firstname', 'shankar'

    UNION ALL SELECT 'firstname', 'dany'

    SELECT

    CASE WHEN = 'firstname' THEN Value END AS FirstName

    FROM

    @table

    ORDER BY

    CASE WHEN = 'firstname' THEN Value END

    Hope that helps.

    Thanks,

    Simon



    MCSE: Data Platform
    MCSE: Business Intelligence
    Follow me on Twitter: @WazzTheBadger
    LinkedIn Profile: Simon Osborne

  • even easier 😉

    DECLARE @table TABLE

    (

    [Key] VARCHAR(50),

    Value VARCHAR(50)

    )

    INSERT INTO @table

    SELECT 'firstname', 'surya'

    UNION ALL SELECT 'firstname', 'rakhi'

    UNION ALL SELECT 'firstname', 'venkat'

    UNION ALL SELECT 'firstname', 'shankar'

    UNION ALL SELECT 'firstname', 'dany'

    SELECT

    [value] AS FirstName

    FROM

    @table

    ORDER BY

    [Value]

  • I suspect that the OP has more than one "key" name! 😉



    MCSE: Data Platform
    MCSE: Business Intelligence
    Follow me on Twitter: @WazzTheBadger
    LinkedIn Profile: Simon Osborne

  • Easier and Correcter 😉

    SELECT [firstname] = value

    FROM test

    WHERE key = 'firstname'


    [font="Arial"]Low-hanging fruit picker and defender of the moggies[/font]

    For better assistance in answering your questions, please read this[/url].


    Understanding and using APPLY, (I)[/url] and (II)[/url] Paul White[/url]

    Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]

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

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