if object_id('test') is not null drop table test
select '2001' as 年级, '语文' as 课目, 20 as 人数
into test
union select '2001', '数学', 15
union select '2002', '语文', 20
union select '2002', '数学', 15    
union select '2003', '语文', 20
union select '2003', '数学', 15select * from testdeclare @s varchar(1000)
set @s = 'select 年级' 
select @s =  @s + ', sum(case 课目 when ''' + 课目 + ''' then 人数 end) as ' + 课目
from (select distinct 课目 from test) a
set @s = @s + ' from test group by 年级'
exec(@s)drop table test/*
年级    课目      人数
2001 数学 15
2001 语文 20
2002 数学 15
2002 语文 20
2003 数学 15
2003 语文 20         
*//*
年级    数许    语文
2001 15 20
2002 15 20
2003 15 20
*/