Jason Cohen
Jason Cohen

Reputation: 83021

Oracle: Combine multiple results in a subquery into a single comma-separated value

I'm trying to convert a single-columned subquery into a command-separated VARCHAR-typed list of values.

This is identical to this question, but for Oracle rather than SQL Server or MySQL.

Upvotes: 10

Views: 40196

Answers (4)

Leigh Riffel
Leigh Riffel

Reputation: 6641

11.2 introduced LISTAGG, which unlike WM_CONCAT is documented. A custom aggregate function could also do this.

Upvotes: 3

bluwater2001
bluwater2001

Reputation: 7959

SELECT deptno, wm_concat(ename) AS employees FROM emp GROUP BY deptno;

Reference: http://forums.oracle.com/forums/thread.jspa?messageID=1186901&#1186901

Upvotes: 0

Justin Cave
Justin Cave

Reputation: 231661

There is an excellent summary of the available string aggregation techniques on Tim Hall's site.

Upvotes: 15

Jason Cohen
Jason Cohen

Reputation: 83021

I found this that seems to work. Thoughts?

SELECT SUBSTR (c, 2) concatenated
  FROM (SELECT     SYS_CONNECT_BY_PATH ( myfield, ',') c, r
              FROM (SELECT   ROWNUM ID, myfield,
                             RANK () OVER (ORDER BY ROWID DESC) r
                        FROM mytable
                    ORDER BY myfield)
        START WITH ID = 1
        CONNECT BY PRIOR ID = ID - 1)
 WHERE r = 1;

Upvotes: 5

Related Questions