title: SQL query to compute the sum of differences between amounts
body: <p>I have a table that looks like this:</p>
  
  <pre><code>CustID Year Month Amount
  ------ ---- ----- ------
  11     2012 12    310685
  11     2013 1     312119
  11     2013 2     313929
  11     2013 3     315511
  19     2012 12    189736
  19     2013 1     195161
  19     2013 2     199713
  10     2013 1     448438
  10     2013 2     453850
  10     2013 3     460198
  </code></pre>
  
  <p>I need:</p>
  
  <ol>
  <li>for each CustID, compute the difference of <code>Amount</code> of the current month and <code>Amount</code> of the previous month (if there is no 'previous month', just ignore it - return <code>NULL</code> or <code>0</code> or whatever).</li>
  <li>sum the differences for each month.</li>
  </ol>
  
  <p>Expected results:</p>
  
  <pre><code>Year Month Total
  ---- ----- -----
  2012 12    NULL
  2013 1     6859     // (312119-310685) + (195161-189736) [no diff for CustID = 10 because it has no amount for 2012.12]
  2013 2     11774
  2013 3     7930
  </code></pre>
  
  <p>I tried to do it using CTE and ROW_NUMBER() with self-joining etc., but the query became entangled and I lost my way... Any help will be appreciated.</p>