Calculate stock from two transaction tables to a third one in MySQL -
i have 2 tables, 1 incoming shipments , 1 outgoing. there lot of stock queries in various groupings , need fast, i'd create third table summing above 2 , run queries on that. possible using sql only?
simplified example:
table: incoming id productid amount_in ------------------------ 1 6 100 2 5 300 3 6 50 4 2 10 table: outgoing id productid amount_out ------------------------- 1 5 10 2 5 20 3 6 30 resulting table should contain remaining stock:
table: stock productid amount --------------------- 2 10 5 270 -- 300-10-20 6 120 -- 100+50-30
i have grouped 2 tables using union all, preserve similar records, used insert select statement obtained table inserting product id , sum of amount, multiply amount_out -1 subtract in sum.
insert stock select productid, sum(amount) from( select productid , amount_in amount incoming union select productid , amount_out * -1 amount outgoing) group productid
Comments
Post a Comment