I am trying to create a report that calculates the margin from the underlying database. The problem is that the cost (existing in the buy_order_products table) of the product may change.
The cost of the product with identifier 4022 as of 2017-06-08 is 1110, however its cost is 1094 as of 2017-07-25. This confuses. I can’t get the exact cost for every product I sell.
I wrote a PHP algorithm that processes all orders and purchase orders and uses the oldest value for the newest value. but the algorithm has a very high time complexity. Is it possible to do this only with a mysql query?
Please check below scenario:
The company created an order for the supply of product X: quantity 3, value 10. per day 1
Buyers bought 2 products X selling price: 12 per day 1 (there are still 1 item in inventory with a cost of 10)
The company created an order for the supply of product X: quantity 4, value 9. per day 2
Customers bought 3 products. X Sale price: 12 on day 2.
Buyers bought 2 products. X Sale price: 12 per day. 3
The company created an order for the supply of product X: quantity 2, value 11. per day 3
Buyers bought 2 products. X Sale price: 12 per day. 3
Report:
day 1: sold 2 products X for 12, cost 10, profit: 2 * (12 - 10)
Day 2: 3 products X sold for 12, 1 pc. costs 10, 2 pcs. costs 9,
profit: 1 * (12 - 10) + 2 * (12 - 9)
day 3: sold 2 products X for 12, cost 9, profit: 2 * (12 - 9)
sold 2 products X for 12, cost 11, profit: 2 * (12 - 11)
Thus, the profit from newly sold goods is calculated using their corresponding value. I hope you understand my point.
Databse Structure: 
4 Products from the database

Products Purchase Orders for the Above Products

Products Sold 
Dump file attached here