declare @start_date datetime
set @start_date=(select dateadd(mm,datediff(mm,0,getdate()),0))
--select [id]=identity(int,1,1),* into #T from testQuery
select [id]=identity(int,1,1),* into #TB from T_testQuery
select start_date=@start_date,
A.inrefno,A.indate,A.incbm,A.outrefno,A.outdate,B.outcbm,B.bcbm,A.仓内搬运,A.叉车使用费,A.卡板费 into testqueryall
from #TB A,(select min(id) as id,inrefno,outrefno,sum(incbm)as incbm,sum(outcbm)as outcbm,datediff(day,indate,outdate) as mydate,sum(bcbm)as bcbm from #TB group by inrefno,outrefno,indate,outdate)B
where A.id=B.id
fetch next from T_SC into @StartDate,@inrefno,@incbm,@outrefno,@outdate,@outcbm,@bcbm,@仓内搬运,@叉车使用费,@卡板费
while @@FETCH_STATUS=0
begin
if @outdate is not null
begin
insert Temp_A select @StartDate,@inrefno,@incbm,@outrefno,@outdate,@outcbm,@bcbm,datediff(dd,@StartDate,@outdate),@仓内搬运,@叉车使用费,@卡板费
insert Temp_A select
@StartDate,@inrefno,@bcbm,null,null,null,@bcbm,datediff(dd,@StartDate,cast(year(@StartDate)as varchar)+ '-' +
cast(month(@StartDate)+1 as varchar)+ '-01'),@仓内搬运,@叉车使用费,@卡板费
end
else
insert Temp_A select
@StartDate,@inrefno,@incbm,@outrefno,@outdate,@outcbm,@bcbm,datediff(dd,@StartDate,cast(year(@StartDate) as varchar)+
'-'+ cast(month(@StartDate)+1 as varchar) + '-01'),@仓内搬运,@叉车使用费,@卡板费
fetch next from T_SC into @StartDate,@inrefno,@incbm,@outrefno,@outdate,@outcbm,@bcbm,@仓内搬运,@叉车使用费,@卡板费
end
close T_SC
deallocate T_SC
select * from Temp_A
drop table temp_A
drop table #testinrefno
drop table testTempO
drop table testTempO2
drop table testTempI
drop table testTempI2
drop table testquery
drop table T_testQuery
drop table testqueryall
GO