数据库行列转换【转】

create table tb
(
  Name    varchar(10) ,
  Subject varchar(10) ,
  Result  int
)

insert into tb(Name , Subject , Result) values(‘张三’ , ‘语文’ , 74)
insert into tb(Name , Subject , Result) values(‘张三’ , ‘数学’ , 83)
insert into tb(Name , Subject , Result) values(‘张三’ , ‘物理’ , 93)
insert into tb(Name , Subject , Result) values(‘李四’ , ‘语文’ , 74)
insert into tb(Name , Subject , Result) values(‘李四’ , ‘数学’ , 84)
insert into tb(Name , Subject , Result) values(‘李四’ , ‘物理’ , 94)
go
———
–动态SQL,指subject不止语文、数学、物理这三门课程。
declare @sql varchar(8000)
set @sql = ‘select Name as ‘ + ‘姓名’
select @sql = @sql + ‘ , max(case Subject when ”’ + Subject + ”’ then Result else 0 end) [‘ + Subject + ‘]’
from (select distinct Subject from tb) as a
set @sql = @sql + ‘ from tb group by name’
exec(@sql)
/*
姓名        数学        物理        语文         
———- ———– ———– ———–
李四        84          94          74
张三        83          93          74
*/