declare @i int,@mt varchar(10),@sql varchar(8000)
set @i=1
set @sql=''
while @i<=12
begin
  set @mt=str(@mt)+'月'
  set @sql=@sql+'select '''+@mt+''' 月份,'+
'case when 商品ID=''00001'' then '+@mt+' 0001'+
'case when 商品ID=''00002'' then '+@mt+' 0002'+
'case when 商品ID=''00003'' then '+@mt+' 0003'+
'case when 商品ID=''00004'' then '+@mt+' 0004'+
'case when 商品ID=''00005'' then '+@mt+' 0005'+
'case when 商品ID=''00006'' then '+@mt+' 0006 end from t1 union '
  set @i=@i+1
end
exec(@sql)

解决方案 »

  1.   

    create table prod(商品ID varchar(10),m1 int,m2 int,m3 int,m4 int,m5 int,m6 int,
    m7 int,m8 int,m9 int,m10 int,m11 int,m12 int)
    go
    insert into prod values('00001',20,20,20,20,20,20,20,20,20,20,20,20)
    insert into prod values('00002',20,20,20,20,20,20,20,20,20,20,20,20)
    insert into prod values('00003',20,20,20,20,20,20,20,20,20,20,20,20)
    insert into prod values('00004',20,20,20,20,20,20,20,20,20,20,20,20)
    insert into prod values('00005',20,20,20,20,20,20,20,20,20,20,20,20)
    insert into prod values('00006',20,20,20,20,20,20,20,20,20,20,20,20)
    godeclare @i int,@mt varchar(10),@sql varchar(7000)
    set @i=1
    set @sql=''
    while @i<=12
    begin
      set @mt='m'+ltrim(str(@i))
      set @sql=@sql+'select '''+replicate(' ',2-len(@i))+ltrim(str(@i))+'月'' 月份,'+
    'sum(case when 商品ID=''00001'' then '+@mt+' end) ''0001'','+
    'sum(case when 商品ID=''00002'' then '+@mt+' end) ''0002'','+
    'sum(case when 商品ID=''00003'' then '+@mt+' end) ''0003'','+
    'sum(case when 商品ID=''00004'' then '+@mt+' end) ''0004'','+
    'sum(case when 商品ID=''00005'' then '+@mt+' end) ''0005'','+
    'sum(case when 商品ID=''00006'' then '+@mt+' end) ''0006'''+
    ' from prod group by '+@mt+' union '
     set @i=@i+1
    end
    set @sql=left(@sql,len(@sql)-len(' union '))
    exec(@sql)results:
    月份   0001        0002        0003        0004        0005        0006        
    ---- ----------- ----------- ----------- ----------- ----------- ----------- 
     1月  20          20          20          20          20          20
     2月  20          20          20          20          20          20
     3月  20          20          20          20          20          20
     4月  20          20          20          20          20          20
     5月  20          20          20          20          20          20
     6月  20          20          20          20          20          20
     7月  20          20          20          20          20          20
     8月  20          20          20          20          20          20
     9月  20          20          20          20          20          20
    10月  20          20          20          20          20          20
    11月  20          20          20          20          20          20
    12月  20          20          20          20          20          20