在 Oracle 11g 中将列转换为行
Posted
技术标签:
【中文标题】在 Oracle 11g 中将列转换为行【英文标题】:Converting column to rows in Oracle 11g 【发布时间】:2015-01-20 13:23:30 【问题描述】:我有一张这样的桌子:
+----+----------+----------+----------+-----------+----------+----------+
| 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】:从列到行的转换实际上是一个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 |
【讨论】:
真的很好。我正在使用第二种方式。我看到它不会自动选择好的空值。但是如果将来我需要有空值,有没有办法?以上是关于在 Oracle 11g 中将列转换为行的主要内容,如果未能解决你的问题,请参考以下文章