declare @s varchar(8000)
set @s = ''select @s = @s + ',' + 单位 '=sum(case b.序号 when '+rtrim(序号)+' then 1 else 0 end)'
from table2 group by 序号,单位set @s = 'select a.类别'+@s+' from table1 a,table2 b where a.序号=b.序号 group by a.类别'exec(@s)