select id
,[name1]=sum(case name when 'name1' then num end)
,[name2]=sum(case name when 'name2' then num end)
,[name3]=sum(case name when 'name3' then num end)
from table2 group by id
--创建测试表
create table table1(id int,name varchar(10))
insert into table1
select 1,'name1'
union all select 2,'name2'
union all select 3,'name3'
create table table2(ID int,Name varchar(10),Num int)
insert into table2
select 10,'name1',1
union all select 10,'name2',1
union all select 10,'name2',1
union all select 10,'name3',1
--查询处理
declare @s varchar(8000)
set @s=''
select @s=@s+',['+name+']=sum(case name when '''
+name+''' then num end)'
from table1
exec('select id'+@s+' from table2 group by id')
declare @s varchar(8000)
set @s=''
select @s=@s+',['+name+']=sum(case name when '''
+name+''' then num end)'
from table1
exec('select id'+@s+' from table2 group by id')