当前位置: 代码迷 >> Sql Server >> ,将几个行 旋转90度
  详细解决方案

,将几个行 旋转90度

热度:35   发布时间:2016-04-24 20:31:58.0
求助,求助,将几个行 旋转90度
表一
张三     178cm   80kg   10   21 
王五      180    90     4    23
赵六      167    77     3    44



表二


     张三    王五   赵六
     178      180    167
     80       90     77
     10       4      3
     21       23     44


将表一转换成表二 (存储过程实现),可以为 表一插入数据

求大神指教     拜谢      拜谢    拜谢    拜谢    拜谢    拜谢    拜谢    拜谢
存储 数据

------解决方案--------------------
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
  相关解决方案