sql语句交叉报表实现

来源:互联网 发布:守望先锋安娜伤害数据 编辑:程序博客网 时间:2024/05/16 16:23

select isnull(aa.ProductSortCode,'')+'`'+ isnull(aa.ProductCode,'') KeyEx
     ,aa.*,bb.TheName ProductName,bb.ConfigName,ProductSortName,cc.TheName ClientName
into #crosstab
from
(
select a.ProductCode,a.ProductSortCode,b.ClientCode
     ,Sum(a.Number) Number,Sum(a.SaleMoney) SaleMoney,Sum(a.TotalMoney) TotalMoney
from tbSaleOutItem a
Left Outer Join tbSaleOut b on a.BillNo = b.BillNo
Group by a.ProductCode,a.ProductSortCode,b.ClientCode
) aa
Left Outer Join vDatumProduct     bb on aa.ProductCode = bb.TheCode and aa.ProductSortCode=bb.ProductSort
Left Outer Join vDatumAllCustomer cc on aa.ClientCode = cc.TheCode
order by aa.ClientCode
--存储过程:
--1.用sql语句生成需要排序的交叉报表crosstab(a,b,c)需要b(门店)变为行显示,a(商品),c(数量)


--2.例如字段A要交叉显示,注意要对TempCross(b0排序,创建游标,释放游标
declare
   @AFiled varchar(50),--分组显示的名称
         --交叉表的字段
   @BFiled varchar(10),--Tempcross 构成交叉表的字段
   @BFiledName varchar(10),-----仓库名称
   @TempBField varchar(10),--Tempcross 构成交叉表的字段

   @CFiled varchar(10),--分组统计的数据

   @sql varchar(8000) --构成sql语句

declare currow cursor for
select ClientCode,ClientName from #crosstab
open currow
---初始化分组的名称
set @AFiled='ProductName,ProductSortName'
--初始化要求的字段
set @CFiled='Number'
set @sql = 'select '+@AFiled --得到A字段信息

fetch next from currow into @BFiled,@BFiledName
set @TempBField=''
while @@fetch_status=0
begin
     if @BFiled<>@TempBField
     begin
         select @sql = @sql +', sum(case ClientCode when ''' + @BFiled + ''' then '+@CFiled+' else 0 end) as ''' + @BFiledName+'`'+@CFiled + ''''
     end
set @TempBField=@BFiled 
fetch next from currow into @BFiled,@BFiledName
end
set @sql=@Sql+'from #crosstab group by '+@AFiled
print @sql
--3.执行显示结果
exec (@sql)


--4.释放游标
close currow
deallocate currow
--释放临时表
drop table #crosstab