34,576
社区成员
发帖
与我相关
我的任务
分享
表A
Storageid productid billno billdate rknum
001 00001 DJ001 2017-01-01 10000
001 00001 DJ002 2017-01-02 20000
001 00001 DJ003 2017-01-03 30000
002 00002 DJ004 2017-01-01 10000
002 00002 DJ005 2017-01-02 20000
002 00002 DJ006 2017-01-03 30000
002 00002 DJ007 2017-01-04 10000
表B
Storageid productid cknum
001 00001 36000
002 00002 45800
得到表 C
Storageid productid billno billdate rknum cknum yenum(rknum - cknum)
001 00001 DJ001 2017-01-01 10000 10000 0
001 00001 DJ002 2017-01-02 20000 20000 0
001 00001 DJ003 2017-01-03 30000 6000 24000
002 00002 DJ004 2017-01-01 10000 10000 0
002 00002 DJ005 2017-01-02 20000 20000 0
002 00002 DJ006 2017-01-03 30000 15800 14200
002 00002 DJ007 2017-01-04 10000 0 10000
with tbA(Storageid,productid,billno,billdate,rknum)
as(
select '001','00001','DJ001','2017-01-01',10000 union all
select '001','00001','DJ002','2017-01-02',20000 union all
select '001','00001','DJ003','2017-01-03',30000 union all
select '002','00002','DJ004','2017-01-01',10000 union all
select '002','00002','DJ005','2017-01-02',20000 union all
select '002','00002','DJ006','2017-01-03',30000 union all
select '002','00002','DJ007','2017-01-04',10000),
tbB(Storageid,productid,cknum)
as(
select '001','00001',36000 union all
select '002','00002',45800
),
tbC as(
select tbA.*,cknum,rownum=ROW_NUMBER()over(partition by tbA.storageid,tbA.productid order by billdate) from tbA join tbB on tbA.Storageid=tbB.Storageid and tbA.productid=tbB.productid
),tbD as(select Storageid,productid,billno,billdate,rknum,(case when isnull((select sum(rknum) from tbC tbC2 where tbC1.Storageid=tbC2.Storageid and tbC1.productid=tbC2.productid and tbC2.rownum<tbC1.rownum),0)+tbC1.rknum<=tbC1.cknum then tbC1.rknum else (case when cknum- isnull((select sum(rknum) from tbC tbC2 where tbC1.Storageid=tbC2.Storageid and tbC1.productid=tbC2.productid and tbC2.rownum<tbC1.rownum),0)>=0 then cknum- isnull((select sum(rknum) from tbC tbC2 where tbC1.Storageid=tbC2.Storageid and tbC1.productid=tbC2.productid and tbC2.rownum<tbC1.rownum),0) else 0 end) end) as cknum from tbC tbC1)
select *,rknum - cknum as yenum from tbD