日期:2014-05-19  浏览次数:20491 次

数据展示转化问题
库结构是:姓名、次数、结果

------------------
姓名       次数         结果
A                 1             90
A                 2             120
A                 3             110
A                 4             100
B                 1             100
B                 2             140

现在想展示成
姓名     次数1       次数2         次数3       次数4     ……
  A             90           120             110           100
  B             100         140

如何实现啊?谢谢

------解决方案--------------------
create table #t(sname varchar(20)
,stimes int,recource float)
insert into #t
select 'A ',1,90
union all select 'A ',2,120
union all select 'A ',3,110
union all select 'A ',4,100
union all select 'B ',1,100
union all select 'B ',2,140
go
select * from #t

declare @sql varchar(8000)
set @sql = ' '
select @sql = @sql + ',stime ' + cast(stimes as varchar(3)) + '=sum(case stimes when ' + cast(stimes as varchar(3))+ ' then recource end) '
from #t group by stimes order by stimes
set @sql = 'select sname ' + @sql + ' from #t group by sname '
print @sql

exec(@sql)

drop table #t

------解决方案--------------------
create table tbTest(姓名 varchar(10),次数 int,结果 int)
insert tbTest
select 'A ', 1, 90 union all
select 'A ', 2, 120 union all
select 'A ', 3, 110 union all
select 'A ', 4, 100 union all
select 'B ', 1, 100 union all
select 'B ', 2, 140
--静态的
select * from tbtest
select 姓名,max(case when 次数=1 then 结果 else ' 'end) as 次数1
,max(case when 次数=2 then 结果 else ' 'end) as 次数2
,max(case when 次数=3 then 结果 else ' 'end) as 次数3
,max(case when 次数=4 then 结果 else ' 'end) as 次数4
from tbtest
group by 姓名
--动态的
declare @s varchar(1000)
set @s= 'select 姓名 '
select @s=@s+ ', max( case when 次数= ' ' '+rtrim(次数)+ ' ' ' then 结果 else ' ' ' ' end) as 次数 '+rtrim(次数)
from (select distinct 次数 from tbtest) a
set @s=@s+ ' from tbtest group by 姓名 '
exec(@s)
姓名 次数1 次数2 次数3 次数4
---------- ----------- ----------- ----------- -----------
A 90 120 110 100
B 100 140 0 0

(2 行受影响)

------解决方案--------------------
这个不是限制了只有A、B两个人吗,在实际中会有A、B、C……,那插入tbTest时候就不能向上面这样写了吧
-------------------------------------------
完全可以,没有问题.楼主为什么不用实际数据测试一下呢,实践出真知,再结合print @sql打印出的语句体会一下.
这里的姓名只是分组