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')
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')
set @sql=''select @sql=@sql+'['+name+']=sum(case when name='''+name+''' then num else 0 end),'
from (select distinct name from table1)aset @sql='select '+left(@sql,len(@sql)-1)+' from table1'
select @sqlexec (@sql)
create table table1(name varchar(10),num int)
insert table1 select 'a',1
union all select 'b',2
union all select 'c',3
union all select 'a',4
union all select 'b',5
union all select 'c',6
go---查询语句
select name,sum(num) from table1 group by namego--删除测试
drop table table1