LISTAGG in ORACLE

点点圈 提交于 2021-02-05 06:11:05

问题


I am trying to use LISTAGG() to fetch more than two columns.

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

But it is throwing this error:

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

Can please somebody explain why it is?


回答1:


The LISTAGG analytic function was introduced in Oracle 11g Release 2. So, if you are on older version, you won't be able to use it.

The error seems strange. You should actually get ORA-00904: "DEPTNAME": invalid identifier as the standard EMP table in SCOTT schema doesn't have DEPTNAME column. Also, you should get ORA-00979: not a GROUP BY expression as you did not mention the SELECTed columns in the GROUP BY expression.

Using the standard EMP table in SCOTT schema:

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>



回答2:


Try:

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



回答3:


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;


来源:https://stackoverflow.com/questions/35058645/listagg-in-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!