2

Is it possible to return multiple row values, per same id, as a column?

If my table is:

ID     | Value  |Column_data
--------------------------------  
1      | a      |  DATA1
1      | b      |  DATA1
2      | c      |  DATA2 
2      | x      |  DATA2 
3      | y      |  DATA3 
3      | z      |  DATA3

(Each Id has always 2 values)

The select should return:

1,a,b,DATA1
2,c,x,DATA2
3,y,z,DATA3

Taryn
  • 242,637
  • 56
  • 362
  • 405
yuris
  • 1,109
  • 4
  • 19
  • 33

4 Answers4

1

Or listagg(col2) over (...) in 11g

Plouf
  • 627
  • 3
  • 7
1

You did not state what version of Oracle you are using but if you are using Oracle 11g+, then you can transform this data into columns using the PIVOT function:

select id,
  C1,
  C2,
  column_data
from
(
  select id, value, column_data,
    row_number() over(partition by id order by id, value) rn
  from yourtable
) 
pivot
(
  max(value)
  for rn in ('1' as C1, '2' as C2)
) 
order by id

See SQL Fiddle with Demo.

Prior to Oracle 11g, you could use an aggregate function with a CASE expression to transform the rows into columns:

select id,
  max(case when rn = 1 then value end) C1,
  max(case when rn = 2 then value end) C2,
  column_data
from
(
  select id, value, column_data,
    row_number() over(partition by id order by id, value) rn
  from yourtable
) 
group by id, column_data
order by id

See SQL Fiddle with Demo

The result of both queries is:

| ID | C1 | C2 | COLUMN_DATA |
------------------------------
|  1 |  a |  b |       DATA1 |
|  2 |  c |  x |       DATA2 |
|  3 |  y |  z |       DATA3 |
Taryn
  • 242,637
  • 56
  • 362
  • 405
0

You could use pivot, have a look here:

http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html

0

You can try something like this:

with t as ( select id, Column_data, xmlagg(xmlelement("e", Value)) xl 
from table1
group by id, Column_data)
select id, 
       extract(xl, 'e[1]/text()').getstringval() c1, 
       extract(xl, 'e[2]/text()').getstringval() c2, 
       Column_data
from t

Here is a sqlfiddle demo

A.B.Cade
  • 16,735
  • 1
  • 37
  • 53