create table #saleentry(fcustid int,fcustname varchar(200),flevel1id int,flevel1 varchar(200),flevel2id int,flevel2 varchar(200),flevel3id int, flevel3 varchar(200),flevel4id int,flevel4 varchar(200),fitemid int,fnumber varchar(200),fname varchar(200),famount decimal(28,2),fxh int) insert into #saleentry select * from #saleentry1 order by flevel1,flevel2,flevel3,flevel4 desc
select id=identity(int,0,1),groupid=0,fcustname,fsql=',['+fcustname+']=sum(case fcustname when '''+fcustname+''' then famount else 0 end)' into #temp1 from(select distinct fcustname from #saleentry where fxh<3 ) a
create table #temp(id int IDENTITY(0, 1),groupid int,fcustname varchar(200),fsql varchar(2000))
insert into #temp(groupid,fcustname,fsql)select groupid,fcustname,fsql from #temp1 order by fcustname
select @sql0=@sql0+fsql from #temp where groupid=0 select @sql1=@sql0+fsql from #temp where groupid=1 select @sql2=@sql2+fsql from #temp where groupid=2 select @sql3=@sql3+fsql from #temp where groupid=3 select @sql4=@sql4+fsql from #temp where groupid=4
exec('select flevel1 as 品牌,flevel2 as 类别一,flevel3 as 类别二,flevel4 as 类别三,fnumber,fname,sum(famount) as 总金额'+@sql0+@sql1+@sql2+@sql3+@sql3+'from #saleentry group by flevel1,flevel2,flevel3,flevel4,fnumber,fname')
drop table #temp drop table #temp1
drop table #saleentry1
执行后,得出的表为: 品牌 类别一 类别二 类别三 编码 名称 总金额 客户一 客户二 客户三 …… A AA a k 6 1 2 3 A AB b k1 9 2 3 4 B BB BBB a k 6 1 3 2 B BB BBB b k1 7 2 4 1 B BA BBB a k 8 3 3 2
需要结果是: 品牌 类别一 类别二 类别三 编码 名称 总金额 客户一 客户二 客户三 …… A AA a k 6 1 2 3 A AA小计 6 1 2 3 A AB b k1 9 2 3 4 A AB小计 9 2 3 4 A小计 AA 15 3 5 7 B BB BBB a k 6 1 3 2 B BB BBB b k1 7 2 4 1 B BB BBB小计 b k1 13 3 7 3 B BB小计 b k1 13 3 7 3 B BA BBB a k 8 3 3 2 B BA BBB小计 a k 8 3 3 2 B BA小计 a k 8 3 3 2 B小计 a k 21 6 10 5 总计 36 9 15 12