declare @sql varchar(8000)
set @sql='select 商品名称'
select @sql=@sql+',sum(case 销售日期 when '''+销售日期+''' then 销售数量 else 0 end) ['+销售日期+'月份销售数量]'
from (select distinct month(销售日期) 销售日期  from 表一) a
select @sql=@sql+',avg(销售数量) as 平均销售数量 from 表一 group by 商品名称'
--print @sql
exec(@sql)

解决方案 »

  1.   

    select 商品名称,
    sum(case when month(销售日期) = 6 then 销售数量 else 0 end) as 六月份销售数量,
    sum(case when month(销售日期) = 7 then 销售数量 else 0 end) as 七月份销售数量,
    sum(case when month(销售日期) = 8 then 销售数量 else 0 end) as 八月份销售数量,
    avg(销售数量) as 平均销售数量
    from 表
    group by 商品名称
      

  2.   

    select 商品名称,
    sum(case when convert(varchar(6),销售日期,112) ='200306' then 销售数量 else 0 end) as 六月份销售数量,
    sum(case when convert(varchar(6),销售日期,112) ='200307'  then 销售数量 else 0 end) as 七月份销售数量,
    sum(case when convert(varchar(6),销售日期,112) ='200308'  then 销售数量 else 0 end) as 八月份销售数量,
    avg(销售数量*1.0) as 平均销售数量
    from 表
    group by 商品名称