简体   繁体   中英

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 :

    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.

Use UNPIVOT :

SQL Fiddle

Oracle 11g R2 Schema Setup :

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 :

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 |

You can use 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM