# 库龄分析-先进先出法

31 篇文章 2 订阅
9 篇文章 0 订阅

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



• 1
点赞
• 13
收藏
• 打赏
• 1
评论
12-29 396
08-13 2994
08-06 1213
03-03 1210
08-05 3161
10-09 2580
01-24 4790

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。