Concatenate strings using the GROUP BY statement in SQL Server
In many data analysis scenarios, there is a need to concatenate strings from multiple rows grouped by a common identifier. This allows you to efficiently aggregate and manipulate data for reporting purposes.
To achieve this in SQL Server, you can take advantage of the powerful GROUP BY clause and clever use of the FOR XML and PATH functions. This approach provides an efficient and straightforward solution without using cursors, loops, or user-defined functions.
Consider the following example data:
<code>id Name Value 1 A 4 1 B 8 2 C 9</code>
Your goal is to transform this data into the following output:
<code>id Column 1 A:4, B:8 2 C:9</code>
To accomplish this task, you can use the following SQL query:
<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], STRING_AGG([Name] + ':' + CAST([Value] AS VARCHAR(MAX)), ', ') AS NameValues FROM #YourTable GROUP BY ID DROP TABLE #YourTable</code>
Let’s break down the query:
STRING_AGG
function concatenates the strings within each group into a comma-separated list. This provides a cleaner and more readable solution than the old approach. This SQL query effectively groups the data by the ID column and joins the Name and Value columns of each row within each group to get the desired output. Using STRING_AGG
simplifies the code, making it easier to understand and maintain. This method is highly recommended for SQL Server 2017 and higher.
The above is the detailed content of How to Concatenate Strings Using GROUP BY in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!