SQL查询转置列

时间:2015-06-18 07:16:17

标签: sql oracle11g

我有一个以下结构的表:

id | att1 | att2 | att3
-----------------------
1  |  a1  |  b1  |  c1
2  |  a2  |  b2  |  c2
3  |  a3  |  b3  |  c3

我希望将列转置为每个id的行。像这样:

id  |  attname  |  value
------------------------
1   |   att1    |   a1
1   |   att2    |   b1
1   |   att3    |   c1
2   |   att1    |   a2
2   |   att2    |   b2
2   |   att3    |   c2
3   |   att1    |   a3
3   |   att2    |   b3
3   |   att3    |   c3

我正在阅读PIVOT功能,并不确定它是否可以完成工作或如何使用它。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您可以使用unpivot执行此任务。

SELECT *
FROM   table
UNPIVOT (
value FOR att_name 
IN (att1 as 'att1', att2 as 'att2', att3 as 'att3')
);

答案 1 :(得分:0)

这是另一种方法:

SELECT id,attname, value 
FROM Yourtable 
CROSS APPLY ( VALUES ('att1',att1), ('att2',att2), ('att3',att3)) t(attname, value)

答案 2 :(得分:-1)

执行UNION ALL

select id, 'att1' as attname, att1 as value from tablename
union all
select id, 'att2' as attname, att2 as value from tablename
union all
select id, 'att3' as attname, att3 as value from tablename

请注意,VALUE是SQL中的保留字,因此,如果这是您的真实列名,则需要对其进行双引号"value"

相关问题