declare @int int ,@a varchar(50),@sql varchar(8000)
select * ,0 i into #temp from t1
update #temp
set @int=case when @a=区域 then @int +1 else 1 end,
    @a=区域,@i=@intset @sql='select 区域 ,'
select @sql=@sql+'sum(case i when '''+cast(i as varchar)+''' then s2 else null end) s'+cast(i as varchar)+',' from (select distinct i from #temp)a
select @sql=left(@sql,len(@sql)-1)+ ' from #temp group by 区域'
exec (@sql)

解决方案 »

  1.   

    declare @sql varchar(8000)
    set @sql = 'select 区域'
    select @sql = @sql + ',sum(case 商品 when '''+cast(商品 as varchar)+''' then 销售数量 else 0 end) as '+cast(商品 as varchar)
      from (select distinct 商品 from 有一表) as a
    select @sql = @sql+' from 销售单 group by 区域'exec(@sql)
    go
      

  2.   

    declare @int int ,@a varchar(50),@sql varchar(8000)
    select * ,0 i into #temp from t1
    update #temp
    set @int=case when @a=区域 then @int +1 else 1 end,
        @a=区域,@i=@intset @sql='select 区域 ,'
    select @sql=@sql+'sum(case i when '''+cast(i as varchar)+''' then 销售数量 else null end) s'+cast(i as varchar)+',' from (select distinct i from #temp)a
    select @sql=left(@sql,len(@sql)-1)+ ' from #temp group by 区域'
    exec (@sql)