在Oracle 11g中将列转换为行

时间:2015-01-20 13:23:31

标签: oracle11g unpivot

我有一张这样的表:

+----+----------+----------+----------+-----------+----------+----------+
| ID | AR_SCORE | ER_SCORE | FS_SCORE | CPF_SCORE | IF_SCORE | IS_SCORE |
+----+----------+----------+----------+-----------+----------+----------+
|  1 |       25 |       35 |       45 |        55 |       65 |       75 |
|  2 |       95 |       85 |       75 |        65 |       55 |       45 |
+----+----------+----------+----------+-----------+----------+----------+

我需要提取这个:

+----+----------+-------+
| ID |  SCORE   | VALUE |
+----+----------+-------+
|  1 | AR_SCORE |    25 |
|  1 | ER_SCORE |    35 |
|  2 | AR_SCORE |    95 |
+----+----------+-------+

我读了许多关于如何在oracle中使用数据透视的问题,但是我无法使其工作。

1 个答案:

答案 0 :(得分:3)

从列到行的转换实际上是UNPIVOT。由于您使用的是Oracle 11g,因此有几种方法可以获得结果。

第一种方法是使用SELECT yourcolumn FROM...UNION ALL

的组合
select ID, 'AR_SCORE' as Score, AR_SCORE as value
from yourtable
union all
select ID, 'ER_SCORE' as Score, ER_SCORE as value
from yourtable
union all
select ID, 'FS_SCORE' as Score, FS_SCORE as value
from yourtable
union all
select ID, 'IF_SCORE' as Score, IF_SCORE as value
from yourtable
union all
select ID, 'IS_SCORE' as Score, IS_SCORE as value
from yourtable
order by id

Demo。在Oracle 11g之前,您需要使用UNION ALL来展开数据,但是从该版本开始,UNPIVOT函数已经实现。这将使用更少的代码行获得相同的结果:

select ID, Score, value
from yourtable
unpivot
(
  value
  for Score in (AR_SCORE, ER_SCORE, FS_SCORE, IF_SCORE, IS_SCORE)
) un
order by id

Demo。两者都会给出结果:

| ID |    SCORE | VALUE |
|----|----------|-------|
|  1 | AR_SCORE |    25 |
|  1 | FS_SCORE |    45 |
|  1 | IS_SCORE |    75 |
|  1 | IF_SCORE |    65 |
|  1 | ER_SCORE |    35 |
|  2 | FS_SCORE |    75 |
|  2 | IS_SCORE |    45 |
|  2 | ER_SCORE |    85 |
|  2 | IF_SCORE |    55 |
|  2 | AR_SCORE |    95 |