Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 956
Jason Cohen Avatar asked Jan 29 '09 17:01

Jason Cohen


People also ask

How do I concatenate multiple rows into a single string in Oracle?

You can use listagg() to convert rows into a comma separated string.


3 Answers

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;
like image 187
Jason Cohen Avatar answered Nov 09 '22 09:11

Jason Cohen


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

like image 41
Justin Cave Avatar answered Nov 09 '22 10:11

Justin Cave


11.2 introduced LISTAGG, which unlike WM_CONCAT is documented. We are not on 11.2 yet, so we use a custom aggregate function.

like image 31
Leigh Riffel Avatar answered Nov 09 '22 10:11

Leigh Riffel