title: MySQL query to calculate balance of increments/decrements to product IDs inventory stock level
body: <p>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).</p>
  
  <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>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';
  </code></pre>
  
  <p>I have a <a href="http://www.sqlfiddle.com/#!2/b4c8b/4/0" rel="nofollow noreferrer">fiddle here</a></p>
  
  <p>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. </p>
  
  <p>After some searching I came across <a href="https://stackoverflow.com/questions/10294393/calculate-the-each-productinkcode-stock">this question</a> 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.</p>
  
  <p>--- edit ---</p>
  
  <p>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?</p>