How to use GROUP BY to concatenate strings in SQL Server?

前端 未结 20 2594
无人及你
无人及你 2020-11-21 04:33

How do I get:

id       Name       Value
1          A          4
1          B          8
2          C          9

to

id               


        
20条回答
  •  感情败类
    2020-11-21 05:03

    This is just an addition to Kevin Fairchild's post (very clever by the way). I would have added it as a comment, but I don't have enough points yet :)

    I was using this idea for a view I was working on, however the items I was concatinating contained spaces. So I modified the code slightly to not use spaces as delimiters.

    Again thanks for the cool workaround Kevin!

    CREATE TABLE #YourTable ( [ID] INT, [Name] CHAR(1), [Value] INT ) 
    
    INSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'A', 4) 
    INSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (1, 'B', 8) 
    INSERT INTO #YourTable ([ID], [Name], [Value]) VALUES (2, 'C', 9) 
    
    SELECT [ID], 
           REPLACE(REPLACE(REPLACE(
                              (SELECT [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) as A 
                               FROM   #YourTable 
                               WHERE  ( ID = Results.ID ) 
                               FOR XML PATH (''))
                            , '', ', ')
                    ,'','')
            ,'','') AS NameValues 
    FROM   #YourTable Results 
    GROUP  BY ID 
    
    DROP TABLE #YourTable 
    

提交回复
热议问题