Sql 将多行中的值作为列返回

Sql 将多行中的值作为列返回,sql,oracle,pivot,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的多个行值作为一列返回

如果我的桌子是:

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、数据1
2,c,x,数据2

3,y,z,DATA3

您可以使用pivot,请看这里:


listag(col2)over(…)
在11g中

您可以尝试以下方法:

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

您没有说明您使用的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

在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

两个查询的结果都是:

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

你在找一个交叉表。查找“交叉表”,你会发现一百万个示例。@dasblinkenlight我不需要计算它们,我需要得到它们谢谢,Oracle之前的版本11g@yuris你来了!:)