I have just run across this interesting article here, showing how to simulate wm_concat()
or group_concat()
in Oracle using a hierarchical query and window functions:
SELECT deptno,
LTRIM(MAX(SYS_CONNECT_BY_PATH(ename,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS employees
FROM (SELECT deptno,
ename,
ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY ename) AS curr,
ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY ename) -1 AS prev
FROM emp)
GROUP BY deptno
CONNECT BY prev = PRIOR curr AND deptno = PRIOR deptno
START WITH curr = 1;
Although, I find this not a very readable solution, it's quite interesting, specifically because the CONNECT BY .. STARTS WITH
clause comes after the GROUP BY
clause. According to the specification, this shouldn't be possible. I've tried this using a simple query and it does work, though! The following two queries return the same results:
-- wrong according to the specification:
select level from dual group by level connect by level <= 2;
-- correct according to the specification:
select level from dual connect by level <= 2 group by level;
Is this an undocumented feature? Or just syntax indifference for convenience? Or do the two statements subtly behave differently?