coalesce (or alternative) PIVOT *into* CSV

  • I can't figure out how to add a 'grouping' to the output of this. any help appreciated. Thanks

    current data

    name , SNUM

    bill , 1

    bill , 2

    tom , 3

    tom ,20

    john , 6

    current code:

    DECLARE @SNUMS varchar(max)

    select @SNUMS = COALESCE(@SNUMS,'') + data.SNUM + ','

    from (

    select distinct SNUM from TIMSDATA.dbo.SALMAN

    ) data

    select @SNUMS

    current output:

    '1,2,3,6,20'

    desired output

    name, snums

    'bill','1,2'

    'tom','3,20'

    'john','6'

  • dandenson (4/7/2011)

    desired output

    name, snums

    'bill','1,2'

    'tom','3,20'

    'john','6'

    Hi,

    This is what you are looking for

    go

    declare @Temp table(name varchar(50),Snum varchar(50) )

    insert @Temp values

    ('bill' , 1),

    ('bill' , 2),

    ('tom' , 3),

    ('tom' ,20),

    ('john' , 6)

    SELECT DISTINCT name,SUBSTRING((SELECT ','+Snum AS [text()] FROM @Temp WHERE name = T.name ORDER BY Snum FOR XML PATH( '' ) ), 2,200) AS J

    FROM @Temp AS T;

    Thanks
    Parthi

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

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