sql - Calculate average cost correctly after purchase or delete purchase? -
i have table table_transactions in table when inserting or deleted update 2 tables itemremains , ref_items column 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
my questions how return or calculate if delete 1 of purchase? if delete purchase
3)purchase itema - 10units - 15$ = itemremains qty=20 ref_items avgcost=13,13
trigger work after inserting or deleting on table table_transactions trigger code
declare variable current_qty d_qty; declare variable current_cost d_amt; declare variable new_cost d_amt; begin if (inserting) begin current_qty =0; current_cost =0; new_cost =0; select sum(coalesce(qty,0)) goodsremains goodsid=:new.gdsid :current_qty; select coalesce(gdsavgcost,0) tgoods gdsid=:new.gdsid :current_cost; if (exists(select goodsid goodsremains goodsid = :new.gdsid , storeid = :new.storeid , boxnumber = :new.gdscod)) begin update goodsremains set goodsremains.qty = goodsremains.qty + :new.rgstritemqty * :new.transtype goodsremains.goodsid = :new.gdsid , goodsremains.boxnumber = :new.gdscod , goodsremains.storeid = :new.storeid; end else begin insert 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 gdsid=:new.gdsid; end else if (deleting) begin current_qty =0; current_cost =0; new_cost =0; select sum(coalesce(qty,0)) goodsremains goodsid=:old.gdsid :current_qty; select coalesce(gdsavgcost,0) tgoods gdsid=:old.gdsid :current_cost; update goodsremains set goodsremains.qty = goodsremains.qty - :old.rgstritemqty * :old.transtype goodsremains.goodsid = :old.gdsid , goodsremains.boxnumber = :old.gdscod , 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 gdsid=:old.gdsid; end
Comments
Post a Comment