我可以在oracle中组合或连接列值,如下所示

时间:2013-03-25 10:06:04

标签: sql oracle

基础数据:

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

期望的输出:

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

2 个答案:

答案 0 :(得分:3)

您没有指定Oracle的哪个版本,但在Oracle 11g中,您可以使用LISTAGG

select DEPTNO,
  listagg(ENAME, ',') within group (order by ENAME) as ename
from yourtable
group by DEPTNO

请参阅SQL Fiddle with Demo

在Oracle 10g中,您可以使用wm_concat()

select DEPTNO,
  wm_concat(ENAME) as ename
from yourtable
group by DEPTNO

您还应该能够使用以下内容:

SELECT LRRID,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(CDSID,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM   
(
  SELECT LRRID,
    CDSID,
    ROW_NUMBER() OVER (PARTITION BY LRRID ORDER BY CDSID) AS curr,
    ROW_NUMBER() OVER (PARTITION BY LRRID ORDER BY CDSID) -1 AS prev
  FROM WLRR_LRR_NOTIFY_TABLE
)
GROUP BY LRRID
CONNECT BY prev = PRIOR curr AND LRRID = PRIOR LRRID
START WITH curr = 1;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

嗯,试试吧..

SELECT DEPTNO, LISTAGG(ENAME, ' ') WITHIN GROUP (ORDER BY ENAME) AS ENAME
FROM   <TABLE-NAME>
GROUP BY DEPTNO;