set @str=''
select @str=@str+',['+[F_Cash]+']=
sum(case when [F_Cash]='+QUOTENAME([F_cash],'''')+' then [F_Money] else 0 end)'
from #temp group by [F_Cash]
exec('select [F_UnitID],[F_Unitname] as ''客户'''+@str+',0 as F_BillID,0 as F_check from #temp group by [F_UnitID],[F_UnitName] order by [F_UnitID]')
得到了我想要的数据
客户 中国银行 农业银行
A 300 200
B 500 800
我想在侧面再加个合计,底部也加个合计,如何办
------解决思路----------------------
set @str=''
select @str=@str+',['+[F_Cash]+']=
sum(case when [F_Cash]='+QUOTENAME([F_cash],'''')+' then [F_Money] else 0 end)'
from #temp group by [F_Cash]
SET @str=@str+',[合计]=sum(F_Money)'
exec('select [F_UnitID]=ISNULL(CAST([F_UnitID]AS VARCHAR(10)),''合计'')
,ISNULL([F_UnitName],'''') as ''客户'''+@str+',0 as F_BillID,0 as F_check from #temp
group by [F_UnitID],[F_UnitName] WITH ROLLUP
HAVING GROUPING(F_UnitID)=1 OR GROUPING(F_Unitname)=0
order by GROUPING(F_UnitID),[F_UnitID]')