[英]SQL oracle convert columns to a pair column_name/value
Basically I am having this test table : 基本上我有这个测试表:
dog cat snake
------------------------------
5 7 7
9 8 5
1 3 7
I want to transform it with a SQL request to that : 我想用一个SQL请求将其转换为:
column_name value
---------------------------
dog 5
cat 7
snake 7
dog 9
.. ..
I don't know which Oracle SQL function I can use to achieve that, I heard about Pivot but I can't figure out how it could work in this case. 我不知道我可以使用哪个Oracle SQL函数来实现这一点,我听说过Pivot,但是我不知道在这种情况下它如何工作。
Use UNPIVOT
: 使用UNPIVOT
:
Oracle 11g R2 Schema Setup : 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;
Query 1 : 查询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 |
You can use union all
: 您可以使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.