ORACLE中的LISTAGG

时间:2016-01-28 10:19:24

标签: sql oracle listagg

我正在尝试使用LISTAGG()来获取两列以上的内容。

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

但它抛出了这个错误:

: FROM keyword not found where expected
 00000 -  "FROM keyword not found where expected"
*Cause:    
*Action:
Error at Line: 3 Column: 12

可以请有人解释原因吗?

3 个答案:

答案 0 :(得分:3)

LISTAGG 分析功能是在 Oracle 11g第2版中引入的。因此,如果您使用的是旧版本,则无法使用它。

错误似乎很奇怪。您实际应该得到ORA-00904: "DEPTNAME": invalid identifier,因为EMP架构中的标准SCOTT表没有DEPTNAME列。此外,您应该获得ORA-00979: not a GROUP BY expression,因为您没有在 GROUP BY 表达式中提及 SELECT ed列。

使用 SCOTT 架构中的标准 EMP 表:

SQL> SELECT deptno,
  2    job,
  3    LISTAGG(ename, ',') WITHIN GROUP (
  4  ORDER BY ename) AS employees
  5  FROM emp
  6  GROUP BY deptno,
  7    job;

    DEPTNO JOB       EMPLOYEES
---------- --------- ------------------------
        10 CLERK     MILLER
        10 MANAGER   CLARK
        10 PRESIDENT KING
        20 CLERK     ADAMS,SMITH
        20 ANALYST   FORD,SCOTT
        20 MANAGER   JONES
        30 CLERK     JAMES
        30 MANAGER   BLAKE
        30 SALESMAN  ALLEN,MARTIN,TURNER,WARD

9 rows selected.

SQL>

答案 1 :(得分:2)

尝试:

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

答案 2 :(得分:0)

Oracle 11g:

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

Oracle 10g:

SELECT deptname, deptno, WMSYS.WM_CONCAT(ename) AS employees 
FROM emp 
GROUP BY deptno,job;