我正在寻找一种在Oracle SQL中转置或旋转表的方法。对于这种情况,SELECT中只有一行,但是有多列。
示例:
SELECT
id AS "Id",
name AS "Name",
some_value AS "Favorite color"
FROM
table
WHERE
id = 5;
结果:
id | name | some_value
--- ------ -----------
5 John Orange
我希望看到的是:
Id | 5
Name | John
Favorite color | Orange
我知道PIVOT,但我很难在这种情况下看到一个简单的代码。
答案 0 :(得分:1)
您可以取消显示列以获得此结果,如下所示:
select fld, val
from (
select to_char(id) as "Id", -- convert all columns to same type
name as "Name",
some_value as "Favorite color"
from your_table
where id = 5
) unpivot(val for fld in("Id", "Name", "Favorite color"));
答案 1 :(得分:0)
使用简单的UNION ALL
子句
SELECT 'Id' As field_name, cast( id as varchar2(100)) as Value FROM "TABLE" where id = 5
UNION ALL
SELECT 'Name' , name FROM "TABLE" where id = 5
UNION ALL
SELECT 'Favorite color' , some_value FROM "TABLE" where id = 5;
答案 2 :(得分:0)
Frank Ockenfuss给出了我正在寻找的答案。谢谢,弗兰克!
但是,稍微更改会使列名更改更容易:
SELECT * FROM (
SELECT
TO_CHAR(id) AS id,
TO_CHAR(name) AS name,
TO_CHAR(some_value) AS fav_color
FROM my_table
WHERE id = 5
) UNPIVOT(value FOR key IN(
id AS 'Id',
name AS 'Name',
fav_color AS 'Favorite color'
));
结果:
key | value
-------------- ------
Id 5
Name John
Favorite color Orange