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

前端 未结 20 2534
无人及你
无人及你 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 04:57

    You can improve performance significant the following way if group by contains mostly one item:

    SELECT 
      [ID],
    
    CASE WHEN MAX( [Name]) = MIN( [Name]) THEN 
    MAX( [Name]) NameValues
    ELSE
    
      STUFF((
        SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) 
        FROM #YourTable 
        WHERE (ID = Results.ID) 
        FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
      ,1,2,'') AS NameValues
    
    END
    
    FROM #YourTable Results
    GROUP BY ID
    

提交回复
热议问题