简体   繁体   English

在 Oracle SQL 中使用 group 和 listagg 跨列和行连接

[英]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.注意:不要使用oracle 保留关键字作为列名。 Here GROUP is the oracle reserved keyword.这里的GROUP是 oracle 的保留关键字。

Cheers!!干杯!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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