create table table1(cod char(4),name char(6))
create table table2(part char(4),code char(4),num int)
------------------------------------------------------------------
insert into table1 values('c001','项目一')
insert into table1 values('c002','项目二')
insert into table1 values('c003','项目三')
insert into table2 values('a','c001',15)
insert into table2 values('a','c001',20)
insert into table2 values('b','c001',5)
insert into table2 values('a','c002',1)
insert into table2 values('a','c002',3)
insert into table2 values('a','c003',3)
insert into table2 values('a','c003',5)
-------------------------------------------
declare @s varchar(8000)
set @s =''
select @s=@s+','+b.name+'=sum(case when code='''+a.code+''' then num else 0 end)'
from table2 a,table1 b
where a.code=b.cod
group by a.code,b.name
order by a.code--这句排序
exec('select part '+@s+'
from table2
group by part')