日期:2014-05-17  浏览次数:20403 次

求SQL语句 ,倒推算最早入库时间
我有两个表,表一为库存表,表二为交易记录表(收货表,将数量调整成了负数)

我现在想要的结果是:通过这两个表,知道现有的库存量,最早一次收货是什么时候。
比如表1中10100 中的库存1000个,(1000-500-400-400)<=0(第一次小于等于0) 得出最早一次收货是2013-4-20

表1中的 10157 中的库存量为:2000(2000-400-600-400-600) 得出 2013/2/15

表一:
ITEMID On-hand
10100 1000
10157 2000



表二:
itemid 日期         Qty
10100 2013/6/20 -500
10100 2013/5/23 -400
10100 2013/4/20 -400
10100 2013/4/15 -400

10157 2013/4/15 -400
10157 2013/3/15 -600
10157 2013/2/15 -400
10157 2013/2/15 -600
10157 2013/1/1 -600
sql?语句 库存帐龄

------解决方案--------------------
select a.ITEMID,a.[On-hand]
,max(b.日期) as 日期
from 表一 a,表二 b
where a.ITEMID = b.ITEMID
and a.[On-hand]+(select sum(Qty) from 表二 where ITEMID = a.ITEMID and 日期 >= b.日期)<= 0
group by a.ITEMID,a.[On-hand]

------解决方案--------------------
with a1 (ITEMID,On_hand) as 
(
select 10100,1000 union all
select 10157,2000
)
,a2 (itemid,date,Qty) as
(
select 10100,'2013/6/20',-500 union all
select 10100,'2013/5/23',-400 union all
select 10100,'2013/4/20',-400 union all
select 10100,'2013/4/15',-400 union all
select 10157,'2013/4/15',-400 union all
select 10157,'2013/3/15',-600 union all
select 10157,'2013/2/15',-400 union all
select 10157,'2013/2/15',-600 union all
select 10157,'2013/1/1',-600 
)
,a3 as
(
select *,row_number() over (partition by itemid order by date desc) re from a2
)
,a4 as
(
select b.itemid,b.date,b.re,sum(a.qty) lj_qty
from a3 a
inner join a3 b on a.itemid=b.itemid and a.re<=b.re
group by b.itemid,b.date,b.re
)
,a5 as
(
select a.*,b.On_hand,a.lj_qty+b.On_hand cy
from a4 a