SQL Server 2008数据透视表

时间:2013-06-17 11:01:55

标签: sql-server-2008

如果我有四列名为Person1Person2Person3Value

是否可以将所有三个Person列转换为如下所示(?):

Person Value
-------------------
Person1 10

Person1 50 

Person2 60

Person3 0

我正在使用SQL Server 2008.

1 个答案:

答案 0 :(得分:0)

将多列转换为多行的过程称为UNPIVOT

select person, val
from yourtable
unpivot
(
  val
  for person in (Person1, Person2, Person3)
) unpiv;

这也可以使用UNION ALL查询编写:

select 'person1' as person, person1 as val
from yourtable
union all
select 'person2' as person, person2 as val
from yourtable
union all
select 'person3' as person, person3 as val
from yourtable;

由于您使用的是SQL Server 2008,因此您还可以将CROSS APPLY与VALUES子句一起使用:

select c.person, c.val
from yourtable
cross apply
(
  values
  ('person1', person1),
  ('person2', person2),
  ('person3', person3)
) c (person, val)