title: Compute outstanding amounts in MySQL
body: <p>I am having an issue with a SELECT command in MySQL. I have a database of securities exchanged daily with maturity from 1 to 1000 days (>1 mio rows). I would like to get the outstanding amount per day (and possibly per category). To give an example, suppose this is my initial dataset:</p>
  
  <pre><code>DATE    VALUE    MATURITY
  1       10       3       
  1       15       2
  2       10       1
  3       5        1
  </code></pre>
  
  <p>I would like to get the following output</p>
  
  <pre><code>DATE    OUTSTANDING_AMOUNT
  1       25
  2       35
  3       15
  </code></pre>
  
  <p>Outstanding amount is calculated as the total of securities exchanged still 'alive'. That means, in day 2 there is a new exchange for 10 and two old exchanges (10 and 15) still outstanding as their maturity is longer than one day, for a total outstanding amount of 35 on day 2. In day 3 instead there is a new exchange for 5 and an old exchange from day 1 of 10. That is, 15 of outstanding amount. </p>
  
  <p>Here's a more visual explanation:</p>
  
  <pre><code>Monday      Tuesday     Wednesday
  10          10          10             (Day 1, Value 10, matures in 3 days)
  15          15                         (Day 1, 15, 2 days)
              10                         (Day 2, 10, 1 day)
                          5              (Day 3, 5, 3 days with remainder not shown)
  -------------------------------------
  25          35          15             (Outstanding amount on each day)
  </code></pre>
  
  <p>Is there a simple way to get this result?</p>