日期:2014-05-17 浏览次数:20757 次
create table #tb(name varchar(10),col1 int,col2 int,col3 int,col4 int)
insert into #tb
select '张三',178,80,10,21
union all select '王五',180,90,4,23
union all select '赵六',167,77,3,44
declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim(name)+']=sum(case name when '''+rtrim(name)+''' then col1 end)'
from #tb group by name
exec('select level1'+@sql+'from
(
select name,col1,1 as level1 from #tb
union all select name,col2,2 as level2 from #tb
union all select name,col3,3 as level3 from #tb
union all select name,col4,4 as level4 from #tb
)t group by level1' )
/*
level1 王五 张三 赵六
-----------------------------------
1 180 178 167
2 90 80 77
3 4 10 3