create table ta ( Name varchar(10) , Subject varchar(10) , Result int ) insert into ta(Name , Subject , Result) values(‘张三‘ , ‘语文‘ , 74) insert into ta(Name , Subject , Result) values(‘张三‘ , ‘数学‘ , 83) insert into ta(Name , Subject , Result) values(‘张三‘ , ‘物理‘ , 93) insert into ta(Name , Subject , Result) values(‘李四‘ , ‘语文‘ , 74) insert into ta(Name , Subject , Result) values(‘李四‘ , ‘数学‘ , 84) insert into ta(Name , Subject , Result) values(‘李四‘ , ‘物理‘ , 94) go select * from ta --静态SQL,指subject只有语文、数学、物理这三门课程。 select Name 姓名, max(case Subject when ‘语文‘ then Result else 0 end) 语文, max(case Subject when ‘数学‘ then Result else 0 end) 数学, max(case Subject when ‘物理‘ then Result else 0 end) 物理 from ta group by Name --动态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 ta) as a set @sql = @sql + ‘ from ta group by Name‘ exec(@sql)
时间: 2024-10-12 12:27:12