Home > Database > Mysql Tutorial > How to Combine Multiple SQL Rows into a Single Delimited Field?

How to Combine Multiple SQL Rows into a Single Delimited Field?

DDD
Release: 2025-01-22 00:27:09
Original
778 people have browsed it

How to Combine Multiple SQL Rows into a Single Delimited Field?

SQL Server Function: Combining Multiple SQL Rows into a Single Delimited Field

Efficiently merging multiple rows from a subquery into a single, delimited field within SQL Server requires a robust approach. This article presents two effective techniques, suitable for different SQL Server versions.

FOR XML PATH (SQL Server 2005 and later):

This method, compatible with SQL Server 2005 and subsequent versions, leverages the FOR XML PATH command for string concatenation. Here's an example:

SELECT [VehicleID], [Name], 
       (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX)) 
               FROM [Location] 
               WHERE (VehicleID = Vehicle.VehicleID) 
               FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')) AS Locations
FROM [Vehicle]
Copy after login

This query uses FOR XML PATH to build a comma-separated string of city values for each VehicleID. The STUFF function removes the leading comma.

STRING_AGG (SQL Server 2017 and later):

For SQL Server 2017 and later, the STRING_AGG function offers a cleaner and more efficient solution:

SELECT [VehicleID], [Name], 
       (SELECT STRING_AGG([City], ', ') 
        FROM [Location] 
        WHERE VehicleID = V.VehicleID) AS Locations
FROM [Vehicle] V
Copy after login

STRING_AGG directly concatenates the City values with a specified separator (a comma and space in this case). This approach is generally preferred for its improved readability and performance.

Both methods effectively aggregate data from multiple rows into a single delimited field, simplifying data manipulation within SQL Server. Choose the method best suited to your SQL Server version for optimal results.

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template