Home > Database > Mysql Tutorial > How to Concatenate and Group Multiple Rows in Oracle?

How to Concatenate and Group Multiple Rows in Oracle?

Susan Sarandon
Release: 2025-01-04 02:56:39
Original
572 people have browsed it

How to Concatenate and Group Multiple Rows in Oracle?

Concatenate and Group Multiple Rows in Oracle

In a scenario where you have a table with multiple rows that need concatenation and grouping, the use of LISTAGG function in Oracle 11g provides a straightforward solution:

SELECT group_name, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY GROUP) AS "names"
FROM name_table
GROUP BY group_name
Copy after login

The LISTAGG function aggregates multiple values from a group of rows, separating them with a specified delimiter (here, ','). It simplifies the process of concatenating and grouping, producing the desired result.

For databases prior to Oracle 11g, an alternative approach using analytics is available:

SELECT grp, ltrim(max(sys_connect_by_path(name, ',' )), ',') AS scbp
FROM (
    SELECT name, grp, row_number() OVER (PARTITION BY grp ORDER BY name) AS rn
    FROM tab
)
START WITH rn = 1
CONNECT BY PRIOR rn = rn - 1 AND PRIOR grp = grp
GROUP BY grp
ORDER BY grp
Copy after login

This query leverages the CONNECT BY clause and row_number() analytic function to concatenate and group values iteratively, producing the same output as the LISTAGG method.

The above is the detailed content of How to Concatenate and Group Multiple Rows in Oracle?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template