1

I have Table with values

X     Y     Z  
-     ---   - 
1     abc   P
1     def   Q

I need a normal query (not pl/sql) which can give result as

X  Y        Z
-  -------  ---
1  abc,def  P,Q

i.e Based on column X the values are converted into csv format

There can be more than three columns.

APC
  • 144,005
  • 19
  • 170
  • 281
C Deepak
  • 1,258
  • 1
  • 17
  • 23
  • 2
    what version of Oracle is this? there are `listagr` if you are in Oracle 11g. – Guru Aug 08 '11 at 10:41
  • possible duplicate of [Agregate rows in Oracle SQL statement](http://stackoverflow.com/questions/2667237/agregate-rows-in-oracle-sql-statement) – APC Aug 08 '11 at 11:00
  • My Oracle version is 10.2.0 ..... Its not duplicate of [link](http://stackoverflow.com/questions/2667237/agregate-rows-in-oracle-sql-statement) In that there are only 2 columns ... in this case there can be more than 2 – C Deepak Aug 08 '11 at 11:26

2 Answers2

8

You can choose any one of the following techniques to aggregate your strings

On occasion it is necessary to aggregate data from a number of rows into a single row, giving a list of data associated with a specific value. Using the SCOTT.EMP table as an example, we might want to retrieve a list of employees for each department. Below is a list of the base data and the type of output we would like to return from an aggregate query.

Base Data:

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

Desired Output:

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

Personally, I find this syntax very readable

SELECT x, wm_concat(y), wm_concat(z) 
FROM   xyz
GROUP BY x;
Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
0

For Postgre you could use something like

select X, array_to_string(array_accum(Y), ',') as Y, array_to_string(array_accum(Z), ',') as Z
from Table
group by X

It's array_to_string and array_accum are built-in functions.

J0HN
  • 26,063
  • 5
  • 54
  • 85