将多行的值作为列返回

时间:2013-02-12 09:31:58

标签: sql oracle pivot

是否可以将每个相同ID的多个行值作为列返回?

如果我的表是:

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

(每个Id总是2个值)

选择应返回:

1,A,B,DATA1
2,C,X,DATA2
3,Y,Z,DATA3

4 个答案:

答案 0 :(得分:1)

您没有说明您使用的是哪个版本的Oracle,但如果您使用的是Oracle 11g +,则可以使用PIVOT函数将此数据转换为列:

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

请参阅SQL Fiddle with Demo

在Oracle 11g之前,您可以使用带有CASE表达式的聚合函数将行转换为列:

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

请参阅SQL Fiddle with Demo

两个查询的结果是:

| ID | C1 | C2 | COLUMN_DATA |
------------------------------
|  1 |  a |  b |       DATA1 |
|  2 |  c |  x |       DATA2 |
|  3 |  y |  z |       DATA3 |

答案 1 :(得分:0)

你可以使用数据透视,看看这里:

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

答案 2 :(得分:0)

或11g中的listagg(col2) over (...)

答案 3 :(得分:0)

您可以尝试这样的事情:

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

相关问题