Home >Database >Mysql Tutorial >How Can I Concatenate and Group Rows in Oracle?

How Can I Concatenate and Group Rows in Oracle?

Linda Hamilton
Linda HamiltonOriginal
2025-01-04 22:58:41191browse

How Can I Concatenate and Group Rows in Oracle?

Concatenating and Grouping Multiple Rows in Oracle

In Oracle, the task of concatenating records based on a grouping condition can be challenging. Consider a table like this:

NAME          GROUP_NAME
name1         groupA
name2         groupB
name5         groupC
name4         groupA
name3         groupC

To achieve the desired result of grouping and concatenating the "NAME" column based on "GROUP_NAME", you can leverage the LISTAGG function in Oracle 11g or later:

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

However, if you are working with an Oracle version that does not support LISTAGG, there are alternative methods. One approach utilizes analytical functions:

select grp,
    ltrim(max(sys_connect_by_path
       (name, ',' )), ',') scbp
  from (select name, grp,
            row_number() over
           (partition by grp
            order by name) rn
         from tab
          )
start with rn = 1
connect by prior rn = rn-1
and prior grp = grp
  group by grp
  order by grp

By combining these techniques, you can effectively concatenate and group multiple rows in Oracle, even in the absence of LISTAGG.

The above is the detailed content of How Can I Concatenate and Group Rows in Oracle?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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