title: Electricity Bill tariff slab calculation using SQL
body: <p>I have table "Readings" with the following schema:</p>
  
  <pre><code>----------------------------------------
  |  Id  |        DateTime     |  value  |
  ---------------------------------------
  |  16  |  01/01/19  22:50:59 |    90   | 
  ---------------------------------------
  |  16  |  01/02/19  8:53:11  |    200  | 
  ---------------------------------------
  |  16  |  04/01/19  22:50:59 |    400  |  
  ---------------------------------------
  |  16  |  03/01/19  1:20:00  |    100  |
  ---------------------------------------
  </code></pre>
  
  <p>And Another table "Tariffs" with the following schema:</p>
  
  <pre><code>-------------------------------------------------
  |  Id  |   start_value  | end_value |    rate   |
  -------------------------------------------------
  |  16  |        0       |    100    |    0.2    | 
  -------------------------------------------------
  |  16  |       100      |    500    |    0.25   | 
  ------------------------------------------------
  |  16  |       500      |    1000   |    0.3    |   
  -------------------------------------------------
  </code></pre>
  
  <p>I want to get the total cost as the example here:
  The summation of values is = 90 + 200 + 400 + 100 = 790
  According to the tariff table, the first 100 of the summation will be multiplied by 0.2 the other 400 by 0.25 ...</p>
  
  <pre><code>Then the cost = (100 * 0.2) + (400 * 0.25) + (290 * 0.3) = 207
  </code></pre>