Home >Database >Mysql Tutorial >How to Group Data and Concatenate Values with Comma Separators in SQL?
SQL Grouping and Concatenation with Comma Separators
This guide demonstrates how to write a SQL query that groups data and concatenates aggregated values using comma separators. Imagine a table like this:
<code>| ID | Value | |-----|-------| | 1 | a | | 1 | b | | 2 | c |</code>
The goal is to generate a result set where values for the same ID are combined into a single comma-separated string:
<code>| ID | Value | |-----|-------| | 1 | a,b | | 2 | c |</code>
Solution using FOR XML PATH:
The FOR XML PATH
construct provides an efficient way to accomplish this:
<code class="language-sql">SELECT ID, STUFF((SELECT ', ' + Value FROM YourTable t2 WHERE t1.ID = t2.ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS Values FROM YourTable t1 GROUP BY ID;</code>
The STUFF
function removes the leading comma and space added by the SELECT
statement. This approach is generally preferred for its performance and readability.
Further Reading:
For more advanced scenarios and alternative techniques, explore these resources:
FOR XML PATH
and related functions.This revised response improves clarity, provides a more concise explanation, and offers helpful links for further learning. The image remains in its original position.
The above is the detailed content of How to Group Data and Concatenate Values with Comma Separators in SQL?. For more information, please follow other related articles on the PHP Chinese website!