当前位置: 代码迷 >> Sql Server >> 横向数据怎么竖向显示
  详细解决方案

横向数据怎么竖向显示

热度:0   发布时间:2016-04-27 16:28:46.0
横向数据如何竖向显示?
成绩表:xscj
ID   name   shuxue,yuwen,yingyu,shengwu,dili,tiyu,shijian
1     小张   89           42           90           92             84       80       2005-3-1
2     小李     --     --       --     --       --     --     2005-3-1
3     小张   --       --       --       --     --     --     2005-4-1
4     小张   --       --       --       --     --     --     2005-5-1

现在要取小张的成绩,格式如下:
时间   2005-5-1     2005-4-1   2005-3-1
数学     89               --             --
语文     42               --             --
英语     90               --             --
生物     92               --             --
地理     84               --             --
体育     80               --             --

请高手指点,非常感谢!


------解决方案--------------------
将下表数据:
A b c d e
-------------------- ----------- ----------- ----------- -----------
x 1 2 3 4
y 5 6 7 8
z 9 10 11 12

转化成如下结果:
a x y z
-------------------- ---------- ---------- ----------
b 1 5 9
c 2 6 10
d 3 7 11
e 4 8 12

--生成测试数据
create table test1(A varchar(20),b int,c int,d int,e int)
insert into test1 select 'x ',1,2 ,3 ,4
insert into test1 select 'y ',5,6 ,7 ,8
insert into test1 select 'z ',9,10,11,12


--生成中间数据表
declare @s varchar(8000)
set @s= 'create table test2(a varchar(20) '
select @[email protected]+ ', '+A+ ' varchar(10) ' from test1
set @[email protected]+ ') '
exec(@s)

--借助中间表实现行列转换
declare @name varchar(20)

declare t_cursor cursor for
select name from syscolumns
where id=object_id( 'test1 ') and colid> 1 order by colid

open t_cursor

fetch next from t_cursor into @name

while @@fetch_status=0
begin
exec( 'select '[email protected]+ ' as t into test3 from test1 ')
set @s= 'insert into test2 select ' ' '[email protected]+ ' ' ' '
select @[email protected]+ ', ' ' '+rtrim(t)+ ' ' ' ' from test3
exec(@s)
exec( 'drop table test3 ')
fetch next from t_cursor into @name
end
close t_cursor
deallocate t_cursor


--查看行列互换处理结果
select * from test1
select * from test2

--删除表
drop table test1
  相关解决方案