declare @sql varchar(8000)
set @sql = 'select company.companynumber as [公司编号],company.ShortName as 公司名称'
select @sql = @sql + ',sum(case year when '''+cast([year] as char(4))+''' then quantity end) as ['+cast([year] as char(4))+']' 
from (select distinct year from tempview1) as a
set @sql = @sql + ',sum (quantity) as 总数'
set @sql = @sql+' FROM company left outer join tempview1 on company.companynumber=tempview1.companynumber
group by company.companynumber,company.shortname '
exec @sql