此例子的语句适用于 SQL2005 以上版本
begin
drop table #xstdmxFy
select 提单编号,物料名称+' '+规格型号 as 产品,sum(提单数量) 数量
into #xstdmxFy
from View_XstdQuery
where 是否核销 ='未发运' and 备注 not like '%测试%' and 是否记账 = '是' and 是否发运 = '否'
and 产品类别编号 like '11%'
and 业务日期 between '20170526' and '20170613'
and ((规格型号 not LIKE '%CLCP%') OR
(规格型号 not LIKE '%XNCLCB%') OR
(规格型号 not LIKE '%XNCLCG%') OR
(规格型号 not LIKE '%XNCLTP%') OR
(规格型号 not LIKE '%XNFPGD%') OR
(规格型号 not LIKE '%XNFPXC%') OR
(规格型号 not LIKE '%XNDL%'))
group by 提单编号,物料名称,规格型号,基本单位名称
DECLARE @sql VARCHAR(8000)
SELECT @sql = ISNULL(@sql + ',', '') + 提单编号
FROM #xstdmxFy
GROUP BY 提单编号
SET @sql = 'select m.* , n.总数量,n.平均数 from
(select * from (select * from #xstdmxFy) a pivot (max(数量) for 提单编号 in (' + @sql
+ ')) b) m ,
(select 产品,sum(数量)总数量, cast(avg(数量*1.0) as decimal(18,2)) 平均数 from #xstdmxFy group by 产品) n
where m.产品= n.产品'
EXEC(@sql)
end