购买或删除购买后正确计算平均成本?

时间:2016-02-08 05:24:16

标签: sql firebird firebird-3.0

我有桌子 插入或删除时更新此表中的table_transactions 2桌  itemremains和ref_items列averagecost。

example data formula 
avgcost = (currentqty*currentavgcost+new.qty+new.amt)/(currentqty+new.qty)
1)Purchase ItemA - 10units - 10$  = itemremains qty=10 ref_items avgcost=10

2)Sale ItemA - 4units - 25$  = itemremains qty=6 ref_items avgcost=10

3)Purchase ItemA - 10units - 15$  = itemremains qty=16 ref_items avgcost=13,13
4)Purchase ItemA - 10units - 20$ = itemremains qty=26 ref_items avgcost=15,77

我的问题是 如果删除其中一个购买如何返回或计算? 如果我删除购买

3)Purchase ItemA - 10units - 15$  = itemremains qty=20 ref_items avgcost=13,13

在table table_transactions上插入或删除后触发工作 我的触发代码

declare variable CURRENT_QTY D_QTY;
declare variable CURRENT_COST D_AMT;
declare variable NEW_COST D_AMT;
begin

IF (INSERTING) THEN
  begin
   CURRENT_QTY  =0;
   CURRENT_COST =0;
   NEW_COST     =0;     

  select sum(coalesce(qty,0))
    from GOODSREMAINS
   where GOODSID=:NEW.GDSID     
    INTO :CURRENT_QTY;

  select coalesce(GDSAVGCOST,0)
    from TGOODS
   where GDSID=:NEW.GDSID     
    INTO :CURRENT_COST;

    if (exists(select goodsid from goodsremains where goodsid = :NEW.GDSID and storeid = :NEW.STOREID and boxnumber = :NEW.GDSCOD)) then
        begin
            UPDATE GOODSREMAINS
                   SET GOODSREMAINS.QTY = GOODSREMAINS.QTY + :NEW.RGSTRITEMQTY * :NEW.TRANSTYPE
                        WHERE GOODSREMAINS.GOODSID   = :NEW.GDSID
                               AND GOODSREMAINS.BOXNUMBER = :NEW.GDSCOD
                               AND GOODSREMAINS.STOREID   = :NEW.STOREID;
  end
  else
  begin
    insert into goodsremains (
        goodsid,
        storeid,
        boxnumber,
        qty)
        VALUES (:NEW.GDSID,:NEW.STOREID,:NEW.GDSCOD,:NEW.RGSTRITEMQTY * :NEW.TRANSTYPE);
  end

  NEW_COST = (:CURRENT_QTY*:CURRENT_COST+:NEW.RGSTRITEMQTY*:NEW.RGTRITEMPURCHAMT)/(:NEW.RGSTRITEMQTY+:CURRENT_QTY);  

  update TGOODS
     set GDSAVGCOST=:NEW_COST
   where GDSID=:NEW.GDSID;

end
ELSE IF (DELETING) THEN
   BEGIN
         CURRENT_QTY  =0;
     CURRENT_COST =0;
     NEW_COST     =0;

     select sum(coalesce(qty,0))
    from GOODSREMAINS
   where GOODSID=:OLD.GDSID     
    INTO :CURRENT_QTY;

  select coalesce(GDSAVGCOST,0)
    from TGOODS
   where GDSID=:OLD.GDSID     
    INTO :CURRENT_COST;

     UPDATE GOODSREMAINS
        SET GOODSREMAINS.QTY = GOODSREMAINS.QTY - :OLD.RGSTRITEMQTY * :OLD.TRANSTYPE
      WHERE GOODSREMAINS.GOODSID   = :OLD.GDSID
        AND GOODSREMAINS.BOXNUMBER = :OLD.GDSCOD
        AND GOODSREMAINS.STOREID   = :OLD.STOREID;    



     NEW_COST = ((:CURRENT_QTY-:OLD.RGSTRITEMQTY * :OLD.TRANSTYPE)*:CURRENT_COST-:OLD.RGSTRITEMQTY*:OLD.RGTRITEMPURCHAMT)/:CURRENT_QTY+:OLD.RGSTRITEMQTY;  

  update TGOODS
     set GDSAVGCOST=:NEW_COST
   where GDSID=:OLD.GDSID;
   end    

0 个答案:

没有答案