Home > Database > Mysql Tutorial > How to Concatenate Multiple SQL Rows into a Single Comma-Delimited Column?

How to Concatenate Multiple SQL Rows into a Single Comma-Delimited Column?

Patricia Arquette
Release: 2025-01-21 06:51:12
Original
984 people have browsed it

How to Concatenate Multiple SQL Rows into a Single Comma-Delimited Column?

SQL Techniques for Combining Multiple Rows into a Single Comma-Delimited Field

Aggregating multiple rows of data into a single column, separated by commas, is a frequent requirement in data manipulation. This guide demonstrates how to achieve this concatenation using SQL, focusing on Microsoft SQL Server 2005 and later.

Here's a SQL Server solution:

<code class="language-sql">SELECT t.TicketID,
       STUFF(ISNULL((SELECT ', ' + x.Person
                FROM @Tickets x
               WHERE x.TicketID = t.TicketID
            GROUP BY x.Person
             FOR XML PATH (''), TYPE).value('.','VARCHAR(max)'), ''), 1, 2, '') AS ConcatenatedPersons
  FROM @Tickets t
GROUP BY t.TicketID</code>
Copy after login

This approach employs the STUFF function to efficiently remove a leading comma from the concatenated string. The nested query leverages FOR XML PATH to create a comma-separated list from the individual Person values associated with each TicketID. The ISNULL function handles cases where no persons are associated with a given ticket ID. The result is a single column (ConcatenatedPersons) containing the comma-separated list of persons for each ticket. This method provides a clean and efficient way to achieve the desired concatenation within SQL Server. Adapt this technique to your specific table and column names for optimal results.

The above is the detailed content of How to Concatenate Multiple SQL Rows into a Single Comma-Delimited Column?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template