declare @tb table (name varchar(10),id int) insert into @tb select 'a',1 union select 'a',2 union select 'a',3select name, sum(case id when 1 then id end), sum(case id when 2 then id end), sum(case id when 3 then id end) from @tb group by name
create table tb(name varchar(10),id int) insert into tb select 'a',1 union select 'a',2 union select 'a',3 declare @s varchar(200) set @s='select name' select @s=@s+',sum(case id when '''+rtrim(id)+''' then id end)'from tb group by idselect @s=@s+' from tb group by name' exec(@s)drop table tb
insert into tb
select 'a',1
union select 'a',2
union select 'a',3
declare @s varchar(200)
set @s='select name'
select @s=@s+',sum(case id when '''+rtrim(id)+''' then id end)'from tb group by idselect @s=@s+' from tb group by name'
exec(@s)drop table tb