转动一排

时间:2013-05-17 15:33:00

标签: sql sql-server ms-access pivot

我是使用pivot的新手。如何从此处转移此记录:

P1AVERAGE    P2AVERAGE    P3AVERAGE   -> column name
1.25         1.50         1.75

到此:

AVERAGENAME    AVERAGESCORE
p1Average      1.25
p2Average      1.50
p3Average      1.75

我正在使用SQL Server和MS Access 2007。

2 个答案:

答案 0 :(得分:6)

你要做的是UNPIVOT而不是PIVOT,这使得列回到行,它与枢轴相反。

对于SQL Server ,请使用UNPIVOT表格运算符:

SELECT *
FROM tablename AS t
UNPIVOT
(
  AVERAGESCORE
  FOR plaveragename IN([P1AVERAGE], [P2AVERAGE], [P3AVERAGE])
) AS u;

请在此处查看:

答案 1 :(得分:2)

您应该能够在SQL Server和MS Access中使用以下查询。 UNION ALL获取列并将值转换为多行:

select 'P1AVERAGE' as AverageName, P1AVERAGE as AverageScore
from yourtable
union all
select 'P2AVERAGE' as AverageName, P2AVERAGE as AverageScore
from yourtable
union all
select 'P3AVERAGE' as AverageName, P3AVERAGE as AverageScore
from yourtable