我按日期列出了购买清单。 EG:
ItemCode,购买日期,购买数量
对于项目,我有相应的销售交易:
项目,销售日期,销售数量
我希望得到一个SQL查询(没有游标),以获得每个采购订单数量的余额。 I.e将每次购买(先进先出)运行到0.(出于库存老化的目的)
如何将购买加入销售以获得每个购买的库存批次剩余的余额?没有光标可以吗?
答案 0 :(得分:1)
是。
您将两个表union
放在一起,并在结果集上运行总计。
;with cte as
(
select itemcode, purchasedate as tdate, purchaseqty as qty from purchases
union
select itemcode, salesdate, salesqty from sales
)
select
t1.*,
SUM(t2.qty)
from cte t1
left join cte t2
on t1.tdate>=t2.tdate
and t1.item = t2.item
group by t1.item, t1.pdate, t1.qty
为了使股票在任何特定时间保持相同的原则适用。
select p1.*,
case when (select SUM(abs(qty)) from sales) > SUM(p2.qty) then 0
else SUM(p2.qty) - (select SUM(abs(qty)) from sales) end as stockremaining
from purchases p1
left join purchases p2 on p1.item = p2.item
and p2.purchasedate <= p1.purchasedate
group by p1.purchasedate, p1.item, p1.qty
给出
1 2012-01-01 10 0
1 2012-01-10 5 4