I need to calculate - let's say - item prices based on purchase price and date (FIFO/LIFO). So, let's say I've made theese purchases:
- 3 x ABC for $100 at 2017-11-10
- 2 x ABC for $80 at 2017-11-12
- 5 x XYZ for $120 at 2017-11-11
- 7 x XYZ for $110 at 2017-11-12
Items first bought determine final product price, so ABC will cost $100 + markup for first 3 items sold, and $80 + markup for another 2.
What I need now is a sort of cache table, that should look like so:
SKU price max_qty
ABC 100 3
ABC 80 5
XYZ 120 5
XYZ 110 12
Please note that third column contains not purchased quantity, but rather a sort of "cap" of quantity to which this price is referring. That way I can quickly estimate sell price for 4 items of ABC by doing a simple JOIN on max_qty >= basket_qty
. This is important as there will be much more reads than writes to this table.
What i'm struggling with is generating such table in a manner regarding performance and resource cost. I can't do it in a "query per sku" manner, as there can be quite a lot of records to update at a time. I've tried using MySQL variables;
SELECT
sku,
price,
@r := @r + qty AS max_qty
FROM
(SELECT @r := 0) AS r
JOIN
warehouse_items
GROUP BY
sku
ORDER BY
sku, date_in
This resultset would be easly inserted into cache table, but @r doesn't reset for each new sku in the result.