现有一表记录产品进出库
declare @p table ( pid char(3),iodt datetime, qty int)
pid(产品代码) iodt(出入库日期) qty(数量)
001 2004-01-01 10
001 2004-01-03 -8
001 2004-01-04 -1
001 2004-01-05 5
001 2004-01-07 -6
其中数量为正表示入库,数量为负表示出库,现要计算任意日期时库存产品的库存天数。系统默认先进先出。
比如查询2004-01-02日库龄,则为10个、库龄为1天
查询2004-01-03日库龄,则为2个、库龄为2天
查询2004-01-04日库龄,则为1个、库龄为3天
查询2004-01-05日库龄,则为1个、库龄为4天和5个、库龄为0天
查询2004-01-06日库龄,则为1个、库龄为5天和5个、库龄为1天
查询2004-01-07日库龄,则为0个、库龄为0
---------------------------------------------------------------
解答:
select pid,库龄,case when qty>数量 then 数量 else qty end as 数量
from ( select pid,
datediff(day,iodt,@dt) as 库龄,
qty,
( select isnull(sum(qty),0)
from @p
where pid=@pid and iodt<=@dt and (iodt<=a.iodt or (iodt>a.iodt and qty<0))
)
as 数量
from @p a
where pid=@pid and iodt<=@dt and qty>0
) b
where 数量>0