我想聚合字符串并将它们连接起来。这是我正在使用的例子
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.
编辑:所以在下面的示例中,有一些"员工姓名用逗号"。它使用正则表达式提出的答案:
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),
'([^,]+)(,\1)+', '\1'),
',') AS employees
FROM emp e
GROUP BY e.deptno;
此查询的结果不正确:
答案 0 :(得分:1)
替换
FROM emp
与
FROM (SELECT DISTINCT deptno, ename FROM emp)
(来自非Oracle用户,但应该可以使用)
答案 1 :(得分:0)
您可以使用REGEX:
SELECT deptno,
rtrim( regexp_replace( (Listagg(ename,',') within GROUP (ORDER BY ename) OVER ()), '([^-]*)(-\1)+($|-)', '\1\3'), '-') within GROUP (ORDER BY ename) AS employees
FROM emp
GROUP BY deptno;
这是使用crossjoin的方法
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
让我知道他们是否有效