title: Is there any way in SQL or function in MYSQL that sums up all the increments in a column?
body: <p>I want to find a way to sum up all the increments in the value of a column. </p>
  
  <p>We provide delivery services to our customers. A customer can pay as he go, but if he pays an upfront fee, he gets a better deal. There is a table that has the balance of the customer across the time. So I want to sum all the increments to the balance. I can't change the way the payment is recorded.</p>
  
  <p>I have alredy coded an stored procedure that works, but is kind slow, so I'm looking for alternatives. I think that, maybe, an sql statement that can do this task, can outperform my stored procedure that has loops.</p>
  
  <p>My stored procedure makes a select of the customer in a given date range, and insert the result in a temp table X. After that, it starts to pop rows from X table, comparing the balance value in that row against the previous row, and detects if there is an increment. If there is not increment, pops another row and do the same routine, if there is an increment, it calculates the difference between that row and the previous, and the result is inserted in another temp table Y.</p>
  
  <p>When there are no rows left, the stored procedure performs a SUM in the temp table Y, and thus, you can know how much the customer has "refilled" its balance.</p>
  
  <p>This is an example of the table X, and the expected result:</p>
  
  <pre><code>DATE        BALANCE
  ----        -------
  2019-02-01  200
  2019-02-02  195    //from 200 to 195 there is a decrement, so it doesn't matter
  2019-02-03  180
  2019-02-04  150
  2019-02-05  175    //there is an increment from 150 to 175, it's 25 that must be inserted in the temp table
  2019-02-06  140
  2019-02-07  180    //there is another increment, from 140 to 180, it's 40
  </code></pre>
  
  <p>So the resulting temp table Y must be something like this:</p>
  
  <pre><code>REFILL
  ------
  25
  40
  </code></pre>
  
  <p>The expected result is 65. My stored procedure returns this value, but as I said, is kind slow (it takes about 22 seconds to process 3900 rows, equivalent to 3 days, aprox), I think is because the loops. I would like to explore another alternatives. Because some details that I don't mention here, for a single costumer, I can have 1300 rows per day (the example is given in days, but I have rows by the minute). My tables are indexed, I think properly. I can't post my stored procedure, but it works as described (I know that "The devil is in the detail"). So any suggestion will be appreciated.</p>