Home > Database > Mysql Tutorial > How Can I Achieve String Aggregation in SQL Server Like Oracle's LISTAGG Function?

How Can I Achieve String Aggregation in SQL Server Like Oracle's LISTAGG Function?

Patricia Arquette
Release: 2025-01-03 20:05:38
Original
821 people have browsed it

How Can I Achieve String Aggregation in SQL Server Like Oracle's LISTAGG Function?

Grouped String Aggregation in SQL Server: Finding a LISTAGG Alternative

In SQL Server, string aggregation can be a challenge. Given a table structure that lists car makes and models, you may want to produce a dataset that groups car models by make and concatenates their values into a single column, similar to the LISTAGG function in Oracle.

To achieve this in SQL Server, you can utilize the FOR XML PATH method. Consider the following query:

SELECT CarMakeID,
       CarMake,
       (SELECT ModelNames.ModelNames
        FROM (SELECT DISTINCT CarModel AS ModelNames
              FROM CarModels
              WHERE CarMakeID = make.CarMakeID
              FOR XML PATH('')
             ) AS ModelNames
       ) AS CarModels
FROM CarMakes make
Copy after login

The subquery (SELECT ModelNames.ModelNames... concatenates the distinct model names for each car make using the FOR XML PATH('') method. This generates a comma-separated list of models that is then assigned to the CarModels column in the outer query.

By replacing AGG(CarModel) in your original query with the subquery described above, you can achieve the desired grouping and string aggregation in SQL Server.

The above is the detailed content of How Can I Achieve String Aggregation in SQL Server Like Oracle's LISTAGG Function?. 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