0

The Table is in the following format:

ID     Category
1       a
1       b
2       a
2       b
2       c

I want the output in the following format

ID              Category
1                  a,b
2                 a,b,c

Please suggest a efficient way

Arion
  • 31,011
  • 10
  • 70
  • 88
Raj Reddy
  • 37
  • 2
  • 6
  • possible duplicate of [Concatenate values based on ID](http://stackoverflow.com/questions/6603319/concatenate-values-based-on-id) – Mikael Eriksson Mar 05 '12 at 10:46
  • Possible duplicate of [Concatenate many rows into a single text string?](https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string) – sandeep.gosavi Sep 14 '17 at 13:31

3 Answers3

0

try the following query:

 SELECT ID,  
  REPLACE(
    (SELECT  Category AS [data()] 
     FROM TableA  
     WHERE b.ID=ID
     ORDER BY Category FOR XML PATH('')),
     ' ', ', ')
FROM TableB b 
GROUP BY ID
Vikram
  • 8,235
  • 33
  • 47
0

I faced the similar thing last time and I solved it using Procedure. You need to do a loop in Category for particular ID.

chinna_82
  • 6,353
  • 17
  • 79
  • 134
0

Maybe something like this:

Test data

DECLARE @tbl TABLE(ID INT,Category VARCHAR(100))
INSERT INTO @tbl
VALUES
    (1,'a'),
    (1,'b'),
    (2,'a'),
    (2,'b'),
    (2,'c')

Query

;WITH CTE     ----CTE Name
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS RowNbr,
        ID,
        Category
    FROM
        @tbl AS tbl
)
SELECT
    CTE.ID,
    (
        STUFF
            ((
                SELECT
                    ','+Category
                FROM @tbl AS tbl
                WHERE tbl.ID=CTE.ID
                FOR XML PATH('')
                )
        ,1,1,'')
    ) AS Category
FROM
    CTE
WHERE
    CTE.RowNbr=1
Community
  • 1
  • 1
Arion
  • 31,011
  • 10
  • 70
  • 88