先过先出法在很多的企业都非常试用,而基于企业的管理能力与实际业务数据中的不完整性,会造成实际物料的出入库情况是无序的。而管理者需要看到一定期间的物料库龄,特别是对于A,B类物料的关注情况。这样就需要IT部门对这一部分进行模拟用算法进行推演。
给个例子供相关有需要的朋友参考
结果
if OBJECT_ID('tx') is not null begin drop table Tx end create table Tx( id int identity not null, bflag bit, ddate datetime, ccode varchar(3), cinvcode varchar(3), qty int ); insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(1,'2018-5-01','RK1','A',1000) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(1,'2018-5-08','RK2','A',1000) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(1,'2018-5-10','RK3','A',1000) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(1,'2018-5-15','RK4','A',1000) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(0,'2018-5-02','CK1','A',300) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(0,'2018-5-09','CK2','A',500) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(0,'2018-5-10','CK3','A',200) insert into Tx(bflag,ddate,ccode,cinvcode,qty)values(0,'2018-5-16','CK4','A',1000) select case when bflag=1 then '入库' else '出库' end 标识,ddate as 单据日期,ccode as 单据号,cinvcode as 物料,qty as 数量 from tx order by ddate IF OBJECT_ID('TEMPDB..#TX') IS NOT NULL BEGIN DROP TABLE #TX END SELECT ROW_NUMBER()OVER(PARTITION BY CINVCODE,BFLAG ORDER BY CINVCODE,DDATE) AS IDX,BFLAG,DDATE,CCODE,CINVCODE,QTY,QTY AS iqty INTO #TX FROM TX WHERE BFLAG=1; WITH cte as( SELECT IDX,BFLAG,DDATE,ccode,CINVCODE,QTY,iqty FROM #TX WHERE IDX=1 union all SELECT a.IDX,a.BFLAG,a.DDATE,a.ccode,a.CINVCODE,a.QTY,a.iqty+b.iqty as iqty FROM #TX a inner join cte b on a.IDX=b.idx+1 and a.cinvcode=b.cinvcode ) select case when a.bflag=1 then '入库' else '出库' end as 标识,a.ddate as 单据日期,a.ccode as 单据号,a.cinvcode as 物料, a.qty as 数量,a.iqty as 累计入,b.oqty as 累计出,a.iqty-ISNULL(b.oqty,0) as 差值, case when a.iqty-ISNULL(b.oqty,0)>=qty then qty else a.iqty-ISNULL(b.oqty,0) end 单据余量, case when a.iqty-ISNULL(b.oqty,0)>0 then 1 else 0 end as 标志 from cte a left join (select cinvcode,sum(qty) as oqty from tx where bflag=0 group by cinvcode)b on a.cinvcode=b.cinvcode