自动平衡或求和

时间:2015-04-19 09:13:42

标签: sql sql-server-2005

我有一张材料消耗表,同一产品有不同的成本和库存,如下所示

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     

数量必须从头开始自动扣除

1 个答案:

答案 0 :(得分:0)

我使用派生表来计算累计库存(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)