自动平衡或求和
auto balance or summing
我有一个 table 用于 material 消费,相同的产品具有不同的成本和库存,如下所示
itcode cost stock
100 10 100
100 11 110
100 12 500
100 13 200
如果我消耗了 300 个,我需要得到如下结果
itcode cost stock auto-deduct balance_of_stock
100 10 100 100 0
100 11 110 110 0
100 12 500 90 410
数量必须从头自动扣除
我使用派生的 table 来计算累积库存 (rsum)。 CASE 是在计算 auto_deduct 和 balance_of_stock.
时
select itcode,
cost,
stock,
case when rsum - 300 > 0 then stock + 300 - rsum
else stock end as auto_deduct,
case when rsum < 300 then 0
else rsum - 300 end balance_of_stock
from
(select b1.*,
(select sum(stock) from b b3
where b3.itcode = b1.itcode
and b3.cost <= b1.cost) as rsum
from b b1
where (select sum(stock) from b b2
where b2.itcode = b1.itcode
and b2.cost >= b1.cost) >= 300)
我有一个 table 用于 material 消费,相同的产品具有不同的成本和库存,如下所示
itcode cost stock
100 10 100
100 11 110
100 12 500
100 13 200
如果我消耗了 300 个,我需要得到如下结果
itcode cost stock auto-deduct balance_of_stock
100 10 100 100 0
100 11 110 110 0
100 12 500 90 410
数量必须从头自动扣除
我使用派生的 table 来计算累积库存 (rsum)。 CASE 是在计算 auto_deduct 和 balance_of_stock.
时select itcode,
cost,
stock,
case when rsum - 300 > 0 then stock + 300 - rsum
else stock end as auto_deduct,
case when rsum < 300 then 0
else rsum - 300 end balance_of_stock
from
(select b1.*,
(select sum(stock) from b b3
where b3.itcode = b1.itcode
and b3.cost <= b1.cost) as rsum
from b b1
where (select sum(stock) from b b2
where b2.itcode = b1.itcode
and b2.cost >= b1.cost) >= 300)