我这个sql文要用的就是循环求每个月的本部発注数,
use lhw
if exists(select * from tempdb..sysobjects where id=object_id('tempdb..#月別本部発注'))
begin
drop table #月別本部発注
end
create table #月別本部発注 (月 varchar(10),本部発注原価金額 money, 本部発注売価税込金額 money,本部発注売価税抜金額 money)
if exists(select * from tempdb..sysobjects where id=object_id('tempdb..#jan'))
begin
drop table #jan
end
create table #jan(jan varchar(20))
declare @acct_monthfrom varchar(20)
declare @acct_monthto varchar(20)
declare @acct_dayfrom varchar(20)
declare @acct_dayto varchar(20)
set @acct_monthfrom='200905'----開始月
set @acct_monthto='200909'----終り月
insert into #jan
select jan from M_ITEM A
inner join M_ITEM_LEVEL_NEWEST B
on A.ITEM_CD=B.ITEM_CD
and B.PROD_LEVEL4_CD=116
while(@acct_monthfrom<=@acct_monthto)
begin
set @acct_dayfrom= (select min(ACCT_DT) from dbo.M_DATE where ACCT_MONTH=@acct_monthfrom)
set @acct_dayto=(select max(ACCT_DT) from dbo.M_DATE where ACCT_MONTH=@acct_monthfrom)
--insert into #jan
--select jan from M_ITEM A
--inner join M_ITEM_LEVEL_NEWEST B
--on A.ITEM_CD=B.ITEM_CD
--and B.PROD_LEVEL4_CD=116
insert into #月別本部発注
select
@acct_monthfrom as '月',
sum(C.ORDER_COST_AMT) as '本部発注原価金額',
sum(C.ORDER_RETAIL_TAX_INC_AMT) as '本部発注売価税込金額',
sum(C.ORDER_RETAIL_TAX_EXC_AMT) as '本部発注売価税抜金額'
from
ORDER_D_STORE_ITEM C
inner join #jan D
on C.jan=D.jan
where C.ORD_TYP='2' --本部発注
and C.ORDER_DT between @acct_dayfrom and @acct_dayto
set @acct_monthfrom=@acct_monthfrom+1
end
select * from #月別本部発注
绿色代码因为放在了红色处,结果每次循环都会添加大量的jan,数据错误且速度愈来愈慢,呵呵,粗心的代价啊!