SQL查询转置列

SQL查询转置列,sql,oracle11g,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

我有一个结构如下的表:

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函数,不确定它是否能完成任务,也不知道如何使用它。如有任何帮助,我们将不胜感激。

Do
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”

您可以使用unpivot执行此任务

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

以下是另一种方法:

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

MySQL和Oracle是不同的产品,SQL的版本有所不同。您使用的是哪种产品?@jarlh很抱歉,我使用的是Oracle。当您查询同一个表3次时,我不会使用此解决方案。不是最快的方式。