SQL语句由列转行

最近面试一大公司碰到一道题目:
原表:

要求查询的结果如下:

查询语句如下:
declare @sql varchar(8000)
set @sql = 'select name,'
select @sql = @sql + 'sum(case subject when '''+subject+''' 
then score else 0 end) as '''+subject+''','
from (select distinct subject from test_engine) as a
select @sql = left(@sql,len(@sql)-1) + ' from test_engine group by name'
print(@sql)
exec(@sql)

posted @ 2008-03-24 11:12  自助者天助  阅读(1631)  评论(0编辑  收藏  举报