怎样使用sql语句把数据横向显示
请问有什么方法,可以表中的数据横向显示出来
注意:列数固定为6列
表:TableList
ColNum value
10 1
20 2
30 3
40 4
50 5
60 6
10 11
20 12
30 13
40 14
50 15
60 16
得到显示结果:
____________________________
10 |20 | 30 | 40 | 50 | 60 |
---------------------------
1 |2 | 3 | 4 | 5 | 6 |
---------------------------—
11 |12 | 13 | 14 | 15 | 16 |
---------------------------—
问题点数:20、回复次数:1Top
1 楼zjcxc(邹建)回复于 2004-08-24 11:53:54 得分 20
--示例
--示例数据
create table TableList(ColNum int,value int)
insert TableList select 10,1
union all select 20,2
union all select 30,3
union all select 40,4
union all select 50,5
union all select 60,6
union all select 10,11
union all select 20,12
union all select 30,13
union all select 40,14
union all select 50,15
union all select 60,16
go
--查询处理
select id=identity(int,0,1),* into #t from TableList
declare @s varchar(8000)
set @s=''
set rowcount 6
select @s=@s+',['+cast(ColNum as varchar)+']=max(case id%6 when '+cast(id as varchar)+' then value end)'
from #t
set rowcount 0
set @s=stuff(@s,1,1,'')
exec('select '+@s+' from #t group by id/6')
drop table #t
go
drop table TableList
/*--测试结果
10 20 30 40 50 60
----------- ----------- ----------- ----------- ----------- -----------
1 2 3 4 5 6
11 12 13 14 15 16
--*/Top




