---创建SQL语句
create table #DepartCost
(
id int,
Department varchar(20),
Material varchar(20),
Number int
)
insert into #DepartCost values
(1,'厂房1','材料1',1),
(1,'厂房2','材料2',2),
(1,'厂房1','材料3',1),
(1,'厂房3','材料3',1),
(1,'厂房2','材料3',1),
(1,'厂房3','材料1',1),
(1,'厂房1','材料1',2),
(1,'厂房1','材料2',1),
(1,'厂房1','材料3',1)
select Department,
sum(case Material when '材料1' then Number else 0 end) as [材料1],
sum(case Material when '材料2' then Number else 0 end) as [材料2],
sum(case Material when '材料3' then Number else 0 end) as [材料3]
from #DepartCost
group by Department
declare @sql varchar(1000)
set @sql = 'select Department '
select @sql = @sql+', sum(case Material when '''+Material+''' then Number else 0 end) as ['+Material+']' from
(select distinct Material from #DepartCost) as a
select @sql = @sql + ' from #DepartCost group by Department '
exec(@sql)