简体   繁体   中英

Concatenate across columns and rows using group and listagg in Oracle SQL

I have a table like below and would like to group across columns and then rows. I have a solution that somewhat works but is very slow. Is there a more efficient way of doing it?

Thank you

| GROUP | VAL 1 | VAL 2 | VAL 3 | 
|   A   |   1   |    2  |   3   |
|   A   |   4   |   5   |  6    | 
|   B   |   7   |   8   |   9   |
|   C   |   10  |   11  |   12  |

Preferred result is

| GROUP | TEXT |
|   A   |123456|
|   B   | 789  |
|   C   |101112|

This is what I currently have but it is very slow. Is there an alternate solution which groups across columns and rows

    select GROUP,
    listagg(comments,',')
    within GROUP (order by GROUP) "TEXT"
    from
    (select concat(val 1,concat(val 2,val 3)) as Comments, data.* 
    from data)
    group by GROUP;

Thank you

Use the following query where you will directly get concatenated column values:

SELECT
    "GROUP",
    LISTAGG(VAL_1 || VAL_2 || VAL_3)  
        WITHIN GROUP(ORDER BY VAL_1) AS "TEXT"
FROM DATA
GROUP BY "GROUP";

Note : Do not use oracle reserved keywords as the column names. Here GROUP is the oracle reserved keyword.

Cheers!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM