How Can I Aggregate Strings in SQL Server Like Oracle's LISTAGG?
Jan 22, 2025 pm 01:01 PMList Aggregation in SQL Server
SQL Server provides a powerful set of functions for data aggregation, including the ability to concatenate values from multiple rows into a single comma-separated string. Mastering this aggregation method is critical for a variety of data aggregation and presentation tasks.
To achieve the same functionality as Oracle's LISTAGG function in SQL Server, you can use the STRING_AGG function. Introduced in SQL Server 2017, this function allows concatenating strings within a group.
Example
Consider the following dataset:
字段 A | 字段 B |
---|---|
1 | A |
1 | B |
2 | A |
Query:
SELECT FieldA, STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs FROM TableName GROUP BY FieldA ORDER BY FieldA;
Result:
字段 A | FieldBs |
---|---|
1 | A, B |
2 | A |
The STRING_AGG function with the WITHIN GROUP clause ensures that values are concatenated within each group grouped by FieldA. The ORDER BY clause in an aggregate specifies the order in which values should be listed.
For SQL Server versions prior to 2017, you can use a combination of CTE (common table expression) and STUFF functions to achieve the same result. However, for simplicity and compatibility with newer versions, the STRING_AGG function is the recommended solution.
The above is the detailed content of How Can I Aggregate Strings in SQL Server Like Oracle's LISTAGG?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

What is SQLite? Comprehensive overview

Run MySQl in Linux (with/without podman container with phpmyadmin)

Running multiple MySQL versions on MacOS: A step-by-step guide

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?

How do I configure SSL/TLS encryption for MySQL connections?
