declare @sql varchar(8000)
select @sql = isnull(@sql,'') + ',sum(case 名称 when ''' + 名称 + ''' then 数量 else 0 end) [' + 名称 + ']'
from (select distinct 名称 from tb) as a
set @sql = 'select 分部'+@sql + ' from tb group by 分部 union all select ''合计'''+@sql+' from tb'
exec(@sql)
declare @sql varchar(8000)
set @sql = 'select sno=identity(int,1,1),isnull(分部,''合计'') as 分部 '
select @sql = @sql + ' , sum(case 名称 when ''' + 名称 + ''' then 数量 else 0 end) [' + 名称 + ']'
from (select distinct 名称 from tb) as a
set @sql = @sql + ' into ##tmp from tb group by 分部 with rollup'
exec(@sql)