oracle SQL中的组

s3fp2yjn  于 2023-08-03  发布在  Oracle
关注(0)|答案(2)|浏览(99)

假设我有一个表tbl,其中包含以下数据:
| col2| col2 |
| --| ------------ |
| 一个| 1 |
| 二个| 2 |
| 三个| 3 |
| 一个| 1 |
| 二个| 2 |
| 一个| 1 |
| 二个| 2 |
| 三个| 3 |

期望的结果

我想将col 1中的那些在col 2中具有相同值集的项目分组在一起。
例如:
| 列表2| list2 |
| --| ------------ |
| 一个| 1 |
| 二个| 2 |
| 三个| 3 |
| 一个| 1 |
| 二个| 2 |

当前结果

我已经编写了一些SQL来实现这一点,然而,我的最终结果只给了我一个每组col 1一行。
| 列表2| list2 |
| --| ------------ |
| 一、二| 1, 2 |
| 一、二、三| 1, 2, 3 |

select listagg(col1, ', ') set1, la as set2
from (
    select LISTAGG(t.col2, ', ') la, t.col1
    from tbl t
    GROUP BY t.col1
    )
GROUP BY la

字符串

*DDL

CREATE TABLE "TBL" 
   (    "COL1" VARCHAR2(20 BYTE), 
        "COL2" VARCHAR2(20 BYTE)
   );
INSERT INTO TBL VALUES ('A','1');
INSERT INTO TBL VALUES ('A','2');
INSERT INTO TBL VALUES ('A','3');
INSERT INTO TBL VALUES ('B','1');
INSERT INTO TBL VALUES ('B','2');
INSERT INTO TBL VALUES ('C','1');
INSERT INTO TBL VALUES ('C','2');
INSERT INTO TBL VALUES ('C','3');

uubf1zoe

uubf1zoe1#

在大型数据集上不是很有效,但在您的示例中有效:

with data(col1, col2) as (
        select 'A', 1 from dual union all
        select 'A', 2 from dual union all
        select 'A', 3 from dual union all
        select 'B', 1 from dual union all
        select 'B', 2 from dual union all
        select 'C', 1 from dual union all
        select 'C', 2 from dual union all
        select 'C', 3 from dual 
    )
    select cols1, regexp_substr(col2s, '\d+', 1, level) as col2
    from (
        select listagg(col1, ',') within group(order by col1) as cols1, col2s
        from (
            select col1, listagg(col2,',') within group(order by col2) as col2s 
            from data
            group by col1
        )
        group by col2s
    )
    connect by level <= regexp_count(col2s, '\d+')
        and prior cols1 = cols1
        and prior sys_guid() is not null
    ;

A,C 1
A,C 2
A,C 3
B   1
B   2

字符串
或者使用listagg()over(partition)version:

select distinct listagg(distinct col1, ',') within group(order by col1) over(partition by col2s)  as col1s, 
    col2s, col2
from (
    select col1, 
        listagg(col2,',') within group(order by col2)
        over(partition by col1)  as col2s,
        col2
    from data
);

uyto3xhc

uyto3xhc2#

使用LISTAGG两次,一次作为解析函数,然后作为聚合函数:

SELECT LISTAGG(col1, ',') WITHIN GROUP (ORDER BY col1) AS col1,
       col2
FROM   (
  SELECT t.*,
         LISTAGG(col2, ',') WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1)
           AS c2s
  FROM   tbl t
)
GROUP BY col2, c2s
ORDER BY col1, c2s, col2;

字符串
对于样本数据,输出:
| COL2| COL2 |
| --| ------------ |
| 一个| 1 |
| 二个| 2 |
| 三个| 3 |
| 一个| 1 |
| 二个| 2 |
fiddle

相关问题