When processing the string connection in SQL Server,
clause is a powerful tool. Based on a public field, you can effectively combine the relevant string into a single connection result.
GROUP BY
Let's take a look at a scene:
You have a table containing ID, name, and value columns. You want to connect all rows with the same ID to a single line. The line contains columns called Column, which contains a connected string with format: value: value.
For this reason, you can use
and and FOR XML
clause: PATH
GROUP BY
<code class="language-sql">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], 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 FROM #YourTable Results GROUP BY ID DROP TABLE #YourTable</code>
Sub -query uses
FOR XML PATH('')
The string specified by the clause should be regarded as a single value. PATH('')
STUFF
GROUP BY
The above is the detailed content of How Can I Concatenate Strings in SQL Server Using GROUP BY?. For more information, please follow other related articles on the PHP Chinese website!