行列转换等经典SQL语句
转自:http://blog.sina.com.cn/s/blog_3d7bed650100c4ia.html
在企业应用中,经常会开发报表系统,而在报表中又经常用到行列转换,这里有一个经典的应用实例:
原表:
转换后的表:
实例:
Declare @sql varchar(8000)
Set @sql = 'Select Name as 姓名'
Select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result else 0 end) ['+Subject+']'
from (select distinct Subject from cj) as cj
Select @sql = @sql+' from cj group by name'
Exec (@sql)