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)