I am trying to write a query in PHP that will retrieve the number of rows in a database (By date or ID, Descending) needed to match (or exceed) the sum of the quantity column with a given value x.
That number will give me the LIMIT number (x) I need to find the average cost of x number of rows of the cost column.
The idea is to find out the value of my on-hand inventory by going back only as far in the database as the quantity I have on hand. It effectively tells me How much I paid for the last n quantity of an item by looking back x rows.
I have tried to split it into 2 queries, First getting the limit number (inside a loop with $limitNumber increasing by 1 until the sum(quantity) >= given value n:
SELECT sum(Quantity) as theSum
FROM Receiving
WHERE Product='$productID'
ORDER BY ID DESC
LIMIT $limitNumber;
$limitNumber++;
second I would get the average after knowing how to get the limit number. Something like this:
SELECT ID, AVG((Total+Adjustment) / Quantity) as costAvg
FROM Receiving
WHERE Product='$productID'
ORDER BY ID DESC
LIMIT $limitNumber
Basically, I want to be able to take the on-hand quantity of an inventory item and find the cost of that quantity of the items.
ID | Product | Quantity | Cost | Date |
---|---|---|---|---|
1 | Fork | 10 | 5.00 | 2022-04-19 |
2 | Fork | 10 | 5.00 | 2022-04-19 |
3 | Knife | 7 | 5.00 | 2022-04-20 |
4 | Fork | 20 | 10.00 | 2022-04-20 |
5 | Fork | 10 | 5.00 | 2022-04-21 |
For example: If had 30 Forks on hand, and I wanted to know the average cost of the last 30 Forks I purchased, How would I proceed? Obviously the database will be much larger and the idea is to be able to assign a value to on-hand inventory.
UPDATE To make this work I used the following:
SELECT t.ID,
t.Quantity,
(t.Cost) as rowTotal,
@running_total := @running_total + t.Quantity AS cumulative_sum
FROM Receiving t
JOIN (SELECT @running_total := 0) r
WHERE t.Product = '$productID'
HAVING @running_total <=$numberToReach
ORDER BY t.Date DESC
Then, with PHP I summed the rowTotal and divided by the cumulative_sum