I have a table ‘log’ where I’m tracking inventory changes. I’m using credits to denote an increase in stock and debits to denote a decrease (I think from an accounting principle, this is backwards, but it’s what the client desires).
I need to calculate the balance of the debits and credits for each product (denoted by upc field) like a running total — in other words, I want to show the log sorted by timestamp (or by the default order), and every time there is an increment or decrement to any product, show the resulting stock balance at that moment in time due to that specific increment or decrement.
I’ve been able to demonstrate this using this query, but only by singling out a specific product by adding its UPC code as a condition in the where clause:
SELECT
l.id,
l.upc,
l.credit,
l.debit,
@bal := @bal + credit - debit AS balance,
l.timestamp
FROM log l, (SELECT @bal := 0) b
where upc = '677797003424';
I have a fiddle here
The trouble is that when I take out the where clause, the calculation doesn’t take into account that it’s only supposed to operate on each set of UPC codes separately.
After some searching I came across this question and the answer looks like something similar to what I may need, however, it is pertaining not to MySQL, but SQL Server. Also, I’m not sure the result would be the log/tracking format I’ve mentioned above. Specifically, what I want to avoid is showing the final balance on every line. If there are 999 of a product in stock, and four decrements later, there are 995 in stock, then each record that denotes logging a decrement should not show the calculated balance of 995, but instead, the first decrement log should show the resulting balance of 998, the second should show 997, etc.
— edit —
Is there a way to accomplish this without the use of variables? Also, is it possible to have the log sorted by timestamp, so that the products are all mixed up, instead of being ordered together?
Would this work for you?
Edit:
In order to get negative values in @bal you can do the following