title: sql cumulative sum with null values under specific conditions
body: <p>I need to create table with cumulative sum that for:
   - sum of value and null gives null if there isn't further in row any value</p>
  
  <p>My initial table, from which I want to create that cumulative sum looks like:</p>
  
  <pre><code>+--------------------+---------------+------+-----+---------+-------+
  | First_mob          | r2009         | r2010|r2011| r2012   | r2013 |
  +--------------------+---------------+------+-----+---------+-------+
  | 0                  | 1             | NULL |NULL | NULL    |NULL   |
  | 1                  | 3             | 1    | 2   | 3       |3      |
  | 2                  | 6             | 6    | 3   | NULL    |NULL   |
  | 3                  | 10            | 17   | NULL| NULL    |5      |
  | 4                  | 61            | 23   | NULL| 4       |NULL   | 
  +--------------------+---------------+------+-----+---------+-------+
  </code></pre>
  
  <p>Table which I want obtain looks like</p>
  
  <pre><code>+--------------------+---------------+------+-----+---------+-------+
  | First_mob          | r2009         | r2010|r2011| r2012   | r2013 |
  +--------------------+---------------+------+-----+---------+-------+
  | 0                  | 1             | NULL |NULL | NULL    |NULL   |
  | 1                  | 4             | 1    | 2   | 3       |3      |
  | 2                  | 10            | 7    | 5   | 3       |3      |
  | 3                  | 20            | 24   | NULL| 3       |8      |
  | 4                  | 81            | 47   | NULL| 7       |NULL   | 
  +--------------------+---------------+------+-----+---------+-------+
  </code></pre>
  
  <p>My sql code for cumulative sum looks like:</p>
  
  <pre><code>if OBJECT_ID('tempdb..#suma_risk_prestige_nbr') IS NOT NULL  drop table             #suma_risk_prestige_nbr
  select tp1.first_mob_InDef,
         SUM(tp2.r2007) as r2007,
     SUM(tp2.r2008) as r2008,
     SUM(tp2.r2009) as r2009,
     SUM(tp2.r2010) as r2010,
     SUM(tp2.r2011) as r2011,
     SUM(tp2.r2012) as r2012,
     SUM(tp2.r2013) as r2013
  
  
  into #suma_risk_prestige_nbr
  from #risk_prestige_nbr tp1
  inner join #risk_prestige_nbr tp2 on tp1.first_mob_InDef&gt;=tp2.first_mob_InDef
  group by tp1.first_mob_InDef,tp1.r2007,tp1.r2008,tp1.r2009,tp1.r2010,
  tp1.r2011,tp1.r2012,tp1.r2013
  order by tp1.first_mob_InDef,tp1.r2007,tp1.r2008,tp1.r2009,tp1.r2010,
  tp1.r2011,tp1.r2012,tp1.r2013
  </code></pre>
  
  <p>Thanks</p>