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

前端 未结 20 2507
无人及你
无人及你 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:01

    I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&, <, >) which were encoded.

    The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:

    CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)
    
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
    
    SELECT  [ID],
      STUFF((
        SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
        FROM #YourTable WHERE (ID = Results.ID) 
        FOR XML PATH(''),TYPE 
         /* Use .value to uncomment XML entities e.g. > < etc*/
        ).value('.','VARCHAR(MAX)') 
      ,1,2,'') as NameValues
    FROM    #YourTable Results
    GROUP BY ID
    
    DROP TABLE #YourTable
    

    Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF to remove the first two characters.

    The XML encoding is taken care of automatically by using the TYPE directive.

提交回复
热议问题