如何在oracle 9i的查询中实现字符串聚合?

时间:2013-10-18 07:28:02

标签: oracle aggregation oracle9i

如何在oracle 9i中的查询中实现字符串聚合?

LISTAGG不会使用oracle 9i

1 个答案:

答案 0 :(得分:2)

来自here: -

一种方法是编写一个特定的函数来解决问题。

CREATE OR REPLACE FUNCTION get_employees (p_deptno  in  emp.deptno%TYPE)
  RETURN VARCHAR2
IS
  l_text  VARCHAR2(32767) := NULL;
BEGIN
  FOR cur_rec IN (SELECT ename FROM emp WHERE deptno = p_deptno) LOOP
    l_text := l_text || ',' || cur_rec.ename;
  END LOOP;
  RETURN LTRIM(l_text, ',');
END;
/
SHOW ERRORS

然后可以将该函数合并到查询中,如下所示。

COLUMN employees FORMAT A50

SELECT e.deptno,
       get_employees(e.deptno) AS employees
FROM   (SELECT DISTINCT deptno
        FROM   emp) e;

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