MySQL: possible to calculate the total inventory cost based on amount per received order? -


i calculate total inventory cost subtracting received orders till received order quantity matches inventory level. way have accurate cost of total inventory.

i have following table individual order receipt lines. order_receipt_article

id   order_receipt_id   article_id   quantity   price 1    1000               456          10         100 2    1001               456          5          120 3    1002               456          15         140 4    1003               456          20         100 5    1004               456          5          90 

and table inventory invetory

id   article_id   level 1    456          43 

now want total value of stock on hand can calculated like

(5 x 90) + (20 x 100) + (15 x 140) + (3 x 120) = 4910

i post i've tried have no idea start solve this.

/edit

i'm not asking basic sum() have total of 55 received units have 43 in stock. want know exact value of stock based on received units. looking @ first table oldest order (id 1) not used in calculation because within orders 2 t/m 5 have received total of 45.

this should solve issue, uses session variables keep running total of number of units processed. unusually couldn't work without temp table ordering wasn't working properly, way found solve issue.

drop table if exists order_receipt_article_test; create table order_receipt_article_test(id int unsigned, order_receipt_id int unsigned, article_id int unsigned, quantity int unsigned, price int unsigned);  drop table if exists inventory_test; create table inventory_test(id int unsigned, article_id int unsigned, `level` int unsigned);  insert order_receipt_article_test values     (1, 1000, 456, 10, 100),     (2, 1001, 456, 5, 120),     (3, 1002, 456, 15, 140),     (4, 1003, 456, 20, 100),     (5, 1004, 456, 5, 90);  insert inventory_test values     (1, 456, 43);  set @varticleid := 0; set @vcumulativequantity := 0;  drop temporary table if exists zsort;  create temporary table zsort select a.article_id, a.`level`, b.quantity, b.price, b.order_receipt_id      inventory_test left outer join     order_receipt_article_test b on a.article_id = b.article_id order a.article_id, b.order_receipt_id desc;  select article_id, sum(rowprice)     (     select @vcumulativequantity := if(article_id != @varticleid, `level`, @vcumulativequantity) levelreset, if(@vcumulativequantity < quantity, @vcumulativequantity * price, quantity * price) rowprice, @vcumulativequantity := if(@vcumulativequantity < quantity, 0, @vcumulativequantity - quantity) quantityadjust, @varticleid := article_id article_id zsort     ) group article_id; 

regards,

james


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -