--动态SQL
--测试环境
Create Table #(年级 varchar(10),课目 varchar(10),人数 int)
insert into # select '2001','语文',20
union all select '2001','数学',15
union all select '2002','语文',20
union all select '2002','数学',15
union all select '2003','语文',20
union all select '2003','数学',15
--动态SQL
declare @s varchar(2000)
set @s='SELECT 年级'
select @s=@s+',['+课目+']=max(case when 课目='''+课目+''' then 人数 end)'
from #
group by 课目
set @s=@s+' from # group by 年级 '
exec(@s)