SQL oracle将列转换为对column_name / value

时间:2018-07-10 10:07:26

标签: sql oracle pivot unpivot

基本上我有这个测试表:

dog         cat          snake
------------------------------
 5           7             7
 9           8             5
 1           3             7

我想通过SQL请求将其转换为

    column_name           value
    ---------------------------
     dog                    5
     cat                    7
     snake                  7
     dog                    9
      ..                    ..

我不知道我可以使用哪个Oracle SQL函数来实现这一目标,我听说过Pivot,但是我不知道在这种情况下它如何工作。

2 个答案:

答案 0 :(得分:3)

使用UNPIVOT

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name (dog, cat, snake) AS
SELECT 5, 7, 7 FROM DUAL UNION ALL
SELECT 9, 8, 5 FROM DUAL UNION ALL
SELECT 1, 3, 7 FROM DUAL;

查询1

SELECT *
FROM   table_name
UNPIVOT(
  value FOR column_name IN ( dog, cat, snake )
)

Results

| COLUMN_NAME | VALUE |
|-------------|-------|
|         DOG |     5 |
|         CAT |     7 |
|       SNAKE |     7 |
|         DOG |     9 |
|         CAT |     8 |
|       SNAKE |     5 |
|         DOG |     1 |
|         CAT |     3 |
|       SNAKE |     7 |

答案 1 :(得分:0)

您可以使用union all

select 'dog' as col, dog
from table t
union all
select 'cat', cat
from table t
union all
select 'snake', snake
from table t;