sql 纵变横
代码
create table #TempTable (PersonID int, KeCheng varchar(20), FenShu float)
insert into #TempTable
select 1, 'Math',79.1
union
select 1, 'Study',60
union
select 2, 'Math',90
union
select 1, 'Engish',80.1
union
select 1, 'Janpan',79.1
union
select 3, 'Math',80
union
select 4, 'Math',99
select * from #TempTable
declare @strSql varchar(max)
select @strSql = isnull(@strSql+',','') + 'max(case KeCheng when ''' + KeCheng + ''' then FenShu else 0 end) as ' + KeCheng
from (select distinct KeCheng from #TempTable) a
set @strSql = 'Select PersonID, ' + @strSql + ' from #TempTable group by PersonID'
Print @strSql
exec(@strSql)
truncate table #TempTable
drop table #TempTable
create table #TempTable (PersonID int, KeCheng varchar(20), FenShu float)
insert into #TempTable
select 1, 'Math',79.1
union
select 1, 'Study',60
union
select 2, 'Math',90
union
select 1, 'Engish',80.1
union
select 1, 'Janpan',79.1
union
select 3, 'Math',80
union
select 4, 'Math',99
select * from #TempTable
declare @strSql varchar(max)
select @strSql = isnull(@strSql+',','') + 'max(case KeCheng when ''' + KeCheng + ''' then FenShu else 0 end) as ' + KeCheng
from (select distinct KeCheng from #TempTable) a
set @strSql = 'Select PersonID, ' + @strSql + ' from #TempTable group by PersonID'
Print @strSql
exec(@strSql)
truncate table #TempTable
drop table #TempTable
继续追寻。。。。。。