也许varchar(8000)不够用declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',sum(case when 发货网点='''+发货网点+case when 付款方式='小计' then '''' else ''' and 付款方式='+付款方式 end +' then 发货价格 else 0 end) as ['+发货网点+付款方式+']'
from (
select distinct 发货网点,cast(付款方式 as varchar(20)) as 付款方式
from 单据表1
union all
select distinct 发货网点,'小计' as 付款方式
from 单据表1
) as texec('select name'+@sql+',sum(发货价格) as 合计 from 单据表1 a,单据表2 b,单据表2的从表 c,网点表 d where a.BID=c.BID and c.AID=b.Aid and b.到货网点=d.id group by name')