--生成数据处理临时表
select id=identity(int,0,1),gid=0
,a=',['+车道号+']=sum(case 车道号 when '''
+车道号+''' then 数量 else 0 end)'
into # from(select distinct 车道号 from 表) a
--判断需要多少个变量来处理
select @i=max(len(a)) from #
set @i=7800/@i
--分组临时表
update # set gid=id/@i
select @i=max(gid) from #
--生成数据处理语句
select @sqlhead='''select 车类名称'''
,@sqlend=''' from 表 group by 车类名称'''
,@sql1='',@sql2='select ',@sql3='',@sql4=''
while @i>=0
select @ic=cast(@i as varchar),@i=@i-1
,@sql1='@'+@ic+' varchar(8000),'+@sql1
,@sql2=@sql2+'@'+@ic+'='''','
,@sql3='select @'+@ic+'=@'+@ic+'+a from # where gid='+@ic
+char(13)+@sql3
,@sql4=@sql4+',@'+@ic
--交叉表
declare @sql varchar(8000)
set @sql='select 车类名称'
select @sql=@sql+',['+车道号+']=sum(case 车道号 when '''+车道号+''' then 数量 end)' from (select distinct 车道号 from 表) a
exec(@sql+' from 表 group by 车类名称')
declare @sql varchar(8000)
set @sql = 'select 部门'
select @sql = @sql + ',sum(case 种类 when '''+种类+''' then 数量 else 0 end) ['+种类+'数量]'
from (select distinct 种类 from #a) a
declare @sql varchar(8000)
set @sql = 'select 车类名称'
select @sql = @sql + ',sum(case 车道号 when '''+cast(车道号 as varchar(10))+''' then 数量 else 0 end) [车道号'+cast(车道号 as varchar(10))+']'
from (select distinct 车道号 from 你的表) as a
select @sql = @sql+' from 你的表 group by 车类名称'
declare @sql varchar(8000)
set @sql = 'select 车类名称'
select @sql = @sql + ',sum(case 车道号 when '''+cast(车道号 as varchar(10))+''' then 数量 else 0 end) [车道号'+cast(车道号 as varchar(10))+']'
from (select distinct 车道号 from 你的表) as a
select @sql = @sql+' into 你要的新表 from 你的表 group by 车类名称'