聚合和连接字符串而不重复

Aggregate and concatenate strings without duplication

我想聚合字符串并连接它们。这是我正在使用的例子

SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM   emp
GROUP BY deptno;

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK, CLARK,KING,MILLER, MILLER
        20 ADAMS, ADAMS, ADAMS, FORD,JONES,SCOTT,SMITH
        30 ALLEN,BLAKE,JAMES,MARTIN,MARTIN,TURNER,WARD

3 rows selected.

但我希望在连接的字符串中没有重复的结果。

期望的结果:

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 SMITH,FORD,ADAMS,SCOTT,JONES
        30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD

3 rows selected.

编辑: 所以在下面的例子中有一些 "Employeer names with comma"。它使用带有正则表达式的建议答案:

with emp as (
select 10 as deptno, 'clark,1' as ename from dual
union all
select 10, 'clark,1' from dual
union all
select 10, 'clark,1' from dual
union all
select 10, 'bob' from dual
union all
select 10, 'bob' from dual
union all
select 10, 'don' from dual
union all
select 20, 'tim,2' from dual
union all
select 20, 'tim,2' from dual
union all
select 20, 'tim,2' from dual
union all
select 20, 'jack' from dual
union all
select 20, 'mark' from dual
)
SELECT e.deptno, --LISTAGG(e.ename, ',') WITHIN GROUP (ORDER BY e.ename) AS employees,
RTRIM(REGEXP_REPLACE(listagg (e.ename, ',') 
                     WITHIN GROUP (ORDER BY e.ename),
                     '([^,]+)(,)+', ''),
                     ',') AS employees
FROM   emp e
GROUP BY e.deptno;

这个查询的结果不正确:

替换

FROM   emp

FROM (SELECT DISTINCT deptno, ename FROM  emp)

(来自非 Oracle 用户,但应该可以)

您可以使用正则表达式:

SELECT   deptno, 
         rtrim( regexp_replace( (Listagg(ename,',') within GROUP (ORDER BY ename) OVER ()), '([^-]*)(-)+($|-)', ''), '-') within GROUP (ORDER BY ename) AS employees 
FROM     emp 
GROUP BY deptno;

这是一个使用交叉连接的方法

SELECT DISTINCT deptno, 
                b.enames 
FROM   emp a 
       cross join (SELECT Listagg(ename, '-') 
                            within GROUP (ORDER BY ename) enames 
                   FROM   (SELECT DISTINCT enam ename 
                           FROM   emp)) b 

让我知道它们是否有效