横向显示的动态查询语句

table1
name num
a 1
b 2
c 3
a 4
b 5
c 6
写个sql语句要求得到
a b c //列名无所谓
5 7 9
---------------------------------------------------------------

declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',sum(case name when '''+name+''' then num else 0 end) '+name
from table1 group by name
set @sql=right(@sql,len(@sql)-1)
exec('select '+@sql+' from table1')

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus