SQL oracle 将列转换为一对 column_name/value
SQL oracle convert columns to a pair column_name/value
基本上我正在做这个测试 table :
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,但我不知道它在这种情况下如何工作。
您可以使用 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;
使用UNPIVOT
:
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 )
)
| COLUMN_NAME | VALUE |
|-------------|-------|
| DOG | 5 |
| CAT | 7 |
| SNAKE | 7 |
| DOG | 9 |
| CAT | 8 |
| SNAKE | 5 |
| DOG | 1 |
| CAT | 3 |
| SNAKE | 7 |
基本上我正在做这个测试 table :
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,但我不知道它在这种情况下如何工作。
您可以使用 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;
使用UNPIVOT
:
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 )
)
| COLUMN_NAME | VALUE |
|-------------|-------|
| DOG | 5 |
| CAT | 7 |
| SNAKE | 7 |
| DOG | 9 |
| CAT | 8 |
| SNAKE | 5 |
| DOG | 1 |
| CAT | 3 |
| SNAKE | 7 |