转置一张桌子

时间:2012-03-11 08:36:15

标签: oracle oracle11g pivot

在我的数据库中,我有一个表,其中有一列A,各自的值为:

A
--
1
2
3
4
5

有什么方法可以将表格转换为

A|1|2|3|4|5|

我尝试使用PIVOT关键字,但我无法获得结果。

2 个答案:

答案 0 :(得分:0)

create table temp2(a integer);
insert into temp2 values(1);
insert into temp2 values(2);
insert into temp2 values(3);
insert into temp2 values(4);

您的要求不明确,但我尝试使用UNPIVOT。我不知道您希望在结果中有多少列,但我相信这会给您提示您需要继续进行哪些操作。

SELECT
  "Key",
  wm_concat(value)
FROM Temp2
UNPIVOT (
  value FOR "Key" IN (a)
)

<强>输出

Key     WM_CONCAT(VALUE)
--------------------------
A           1,2,4,3

如果你删除了wm_concat函数,那么它将给出以下输出。

 Key    VALUE
--------------------
 A      1
 A      2
 A      4
 A      3
---------------------

答案 1 :(得分:0)

如果您不知道预期会有多少列,那么可以使用XMLAGG 它不会为您提供列,而是为每行提供xml元素。之后,您可以将每个元素提取到一列 看看这个例子:

with t as (select xmlagg(xmlelement("E", a)) a_xml from your_table)
select rtrim(extract(a_xml, 'E[1]/text()')),
       rtrim(extract(a_xml, 'E[2]/text()')),
       rtrim(extract(a_xml, 'E[3]/text()')),
       rtrim(extract(a_xml, 'E[4]/text()')),
       rtrim(extract(a_xml, 'E[5]/text()'))
from t
相关问题