title: Use last value with operations in SQL Server
body: <p>Let's assume I have a table in SQL Server called Budget_Spend like this <a href="https://i.stack.imgur.com/qvP6g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qvP6g.png" alt="Original table"></a></p>
  
  <p>I know, with proper group by, sum and order by reach the next table (it's pretty obvious) <a href="https://i.stack.imgur.com/y8pLD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y8pLD.png" alt="objective table"></a></p>
  
  <p>However, I don't how to replicate "Aviable" column, constructed following the logic:</p>
  
  <ul>
  <li>For the first month, it's Budget - Spend - Taxes</li>
  <li>For the following months is computed like PREVIOUS(Aviable)-CURRENT(Spend)-CURRENT(Taxes)</li>
  </ul>
  
  <p>I've tried to use LAG function without succes (most of my tries didn't run due to syntax problems). </p>
  
  <p>Any idea of doing? I imagine I need LAG and maybe a CASE in order to get the first value.</p>
  
  <p>This is the DDL for creating the table</p>
  
  <pre><code>/* CREATE TABLE */
  CREATE TABLE Budget_Spend(
  Month DOUBLE,
  Budget DOUBLE,
  Spend DOUBLE,
  Taxes DOUBLE);
  
  /* INSERT */
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (1, 1000, 75, 11.25);
  
  
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (1, 1000, 25, 3.75);
  
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (2, 1000, 200, 30);
  
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (3, 1000, 150, 22.5);
  
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (4, 1000, 10, 1.5);
  
  INSERT INTO Budget_Spend(Month, Budget, Spend, Taxes) VALUES
  (4, 1000, 10, 1.5);
  </code></pre>