SQL Code Help

  • Hi everyone,

    Below is a table example (Table name: Dummy)

    Number     Value
    12345          xyz
    12345          abc
    12345          zcd

    I need an SQL query which will give the result set as
    12345  xyz, abc, zcd

    Thanks in advance

  • ashok.theagarajan - Tuesday, June 20, 2017 10:47 PM

    Hi everyone,

    Below is a table example (Table name: Dummy)

    Number     Value
    12345          xyz
    12345          abc
    12345          zcd

    I need an SQL query which will give the result set as
    12345  xyz, abc, zcd

    Thanks in advance


    SELECT
      a.Number
    , Value = STUFF(( SELECT ',' + CAST(b.Value AS VARCHAR)
           FROM Dummy b
           WHERE a.Number = b.Number
           ORDER BY b.Value
           FOR XML PATH(''), TYPE).value('(./text())[1]','VARCHAR(MAX)'
          ), 1, 1, '')
    FROM Dummy a
    GROUP BY a.Number;

  • Thank you !!!!! Works like a charm

  • Or:
    WITH Dummy (Number, [Value]) AS
    (
       SELECT
            a
          , b
       FROM
          (
             VALUES
                  (12345, 'xyz')
                , (12345, 'abc')
                , (12345, 'zcd')) t (a, b)
    )
    SELECT
         a.Number
       , [xyz]
       , [abc]
       , [zcd]
    FROM Dummy
    PIVOT
       (Max(Value) FOR [Value] IN ([xyz]
       , [abc]
       , [zcd])) a;

  • Hey ! Thanks, But as you can see it provides the result set in columns instead of it being on a single column with comma separated values.
    Also, the earlier method works for as many rows as i have the data for.....

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

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