存储过程如下:CREATE PROCEDURE JR_SUM  @sumiPeriod tinyint --查询月份ASBEGIN  
if   object_id('tempdb..##sumJR')   is   not   null   
    drop   table   ##sumJR  
select a.cCusCode,b.cCCName,a.cCusName,a.iCusCreLine,a.cCusDefine1 into #SumKhflTmp  from Customer a ,Customerclass b where a.ccccode=b.ccccode  --客户分类名称
select sum(iDAmount)-sum(iCAmount) sumNcye,cDeptCode into #SumNcyeTmp from ap_detail where iperiod=0 group by cDwCode,cPerson,cDeptCode --年初余额
select sum(iDAmount) sumByfh,cDeptCode into #SumByfhTmp from ap_detail where iperiod=@sumiPeriod group by cDwCode,cPerson,cDeptCode --本月发货
select sum(iDAmount) sumLjfh,cDeptCode into #SumLjfhTmp from ap_detail where iperiod<=@sumiPeriod  and iperiod<>0 group by cDwCode,cPerson,cDeptCode --累计发货
select sum(iCAmount) sumByhk, cDeptCode into #SumByhkTmp from ap_detail where iperiod=@sumiPeriod group by cDwCode,cPerson,cDeptCode --本月回款
select sum(iCAmount) sumLjhk, cDeptCode into #SumLjhkTmp from ap_detail where iperiod<=@sumiPeriod  and iperiod<>0 group by cDwCode,cPerson,cDeptCode --累计回款
--select a.cDeptCode,(a.sumNcye+b.sumLjfh-c.sumLjhk) as sumQmye into #SumQmyeTmp from #SumNcyeTmp a,#SumLjfhTmp b,#SumLjhkTmp c where a.cDeptCode=b.cDeptCode and a.cDeptCode=c.cDeptCode --期末余额
select cDeptCode,max(dVouchDate)  dVouchDate into #sumMbywsj from Ap_Detail group by cDwCode,cPerson,cDeptCode --末笔业务时间 select 
b.cDepname as '部门',
d.cCCName as '客户分类名称',
a.cDwCode as '客户编码',
d.cCusName as '客户名称',
e.sumNcye as '年初余额', 
f.sumByfh as '本月发货',
g.sumLjfh as '累计发货',
h.sumByhk as '本月回款',
i.sumLjhk as '累计回款',
(e.sumNcye+g.sumLjfh-i.sumLjhk) as '期末余额',
d.iCusCreLine as '资信限额',
t.cPersonCode as '责任人编码',
t.cPersonName as '责任人',
d.cCusDefine1 as '客户类别',
u.dVouchDate as '末笔业务时间'
--v.hlState as '高低端分类'
into
##sumJR
from 
Ap_Detail a,
Department b,
Customer c ,
#SumKhflTmp d,
#SumNcyeTmp e,
#SumByfhTmp f,
#SumLjfhTmp g,
#SumByhkTmp h,
#SumLjhkTmp i,
---#SumQmyeTmp s,
Person t,
#sumMbywsj u
where 
a.cDeptCode=b.cDepCode and 
a.cDwCode=d.cCusCode  and
a.cDeptCode=e.cDeptCode and 
a.cDeptCode=f.cDeptCode and
a.cDeptCode=g.cDeptCode and
a.cDeptCode=h.cDeptCode  and
a.cDeptCode=i.cDeptCode and 
--a.cDeptCode=s.cDeptCode  and
a.cPerson=t.cPersonCode and
a.cDeptCode=u.cDeptCode 
group by 
b.cDepname ,
d.cCCName,
a.cDwCode,
d.cCusName,
e.sumNcye,
f.sumByfh,
g.sumLjfh,
h.sumByhk,
i.sumLjhk,
--s.sumQmye,
d.iCusCreLine,
t.cPersonCode,
t.cPersonName,
d.cCusDefine1,
u.dVouchDate
SELECT 
a.*,b.hlstate as '高低端分类' 
FROM 
##sumJR A
LEFT OUTER JOIN 
CusPerD as b 
ON
 (a.客户编码=b.ccuscode and a.责任人编码=b.cperson)END
GO