I have a table that looks like this:
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
I need:
- for each CustID, compute the difference of Amountof the current month andAmountof the previous month (if there is no 'previous month', just ignore it - returnNULLor0or whatever).
- sum the differences for each month.
Expected results:
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
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.
 
    