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

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

    didn't see any cross apply answers, also no need for xml extraction. Here is a slightly different version of what Kevin Fairchild wrote. It's faster and easier to use in more complex queries:

       select T.ID
    ,MAX(X.cl) NameValues
     from #YourTable T
     CROSS APPLY 
     (select STUFF((
        SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX))
        FROM #YourTable 
        WHERE (ID = T.ID) 
        FOR XML PATH(''))
      ,1,2,'')  [cl]) X
      GROUP BY T.ID
    

提交回复
热议问题