如何将旋转列转换为行?

时间:2012-12-10 13:03:23

标签: sql sql-server-2008 tsql unpivot

我有一个包含

等结果的表格
Donna F. Carreras|Alexander J. Deborde|John  Ford|Marjorie M. Lee| Crystal C Zhu
176          |    246         |     312  |           502 |    19969

我希望它显示为:

176     Donna F. Carreras
246     Alexander J. Deborde
312     John Ford
502     Marjorie M. Lee
19969   Crystal C Zhu

1 个答案:

答案 0 :(得分:2)

在SQL Server中,您可以应用UNPIVOT功能:

select value, col
from yourtable
unpivot
(
  value
  for col in ([Donna F. Carreras], [Alexander J. Deborde], 
              [John Ford], [Marjorie M. Lee], [Crystal C Zhu])
) un

请参阅SQL Fiddle with Demo

或者您可以使用UNION ALL查询:

select [Donna F. Carreras] value, 'Donna F. Carreras' col
from yourtable
union all
select [Alexander J. Deborde] value, 'Alexander J. Deborde' col
from yourtable
union all
select [John Ford] value, 'John Ford' col
from yourtable
union all
select [Marjorie M. Lee] value, 'Marjorie M. Lee' col
from yourtable
union all
select [Crystal C Zhu] value, 'Crystal C Zhu' col
from yourtable

请参阅SQL Fiddle with Demo

两者产生相同的结果:

| VALUE |                  COL |
--------------------------------
|   176 |    Donna F. Carreras |
|   246 | Alexander J. Deborde |
|   312 |            John Ford |
|   502 |      Marjorie M. Lee |
| 19969 |        Crystal C Zhu |