title: Calculating running totals for partitions of data
body: <p>I have table named #t1 and three columns. CODE, Column1, and Column2.</p>
  
  <pre><code>        create table #t1 (
          CODE  NVARCHAR(20),
          COLUMN1  NUMERIC(18,2),
          COLUMN2  NUMERIC(18,2) 
                                )
  </code></pre>
  
  <p>And i have some data:</p>
  
  <pre><code>      INSERT INTO #t1 (CODE,COLUMN1,COLUMN2)
  VALUES ('432', 0,100),
         ('TOTAL FOR 432',0,100),
         ('4320001',0,250),
         ('4320001',50,0),
         ('4320001',0,140),
         ('4320001',300,0),
         ('TOTAL FOR 4320001',350,390),
         ('432002',200,0),
         ('432002',0,100),
         ('TOTAL FOR 432002',200,100)
  
  
  
  
         drop table #t1
  </code></pre>
  
  <p>I want to have 4 column (named BALANCE). Balance must be column that represent running totals between two columns (Column1 - Column2) for each group of data. For each group total must start from zero.</p>
  
  <p>Output:</p>
  
  <pre><code>             CODE                    COLUMN1        COLUMN2        BALANCE
               432                      0.00           100.00         -100
     TOTAL     432                      0.00           100.00         -100
           4320001                      0.00           250.00         -250   
           4320001                     50.00             0.00         -200
           4320001                      0.00           140.00         -340
           4320001                    300.00             0.00          -40
     TOTAL 4320001                    350.00           390.00          -40
            432002                    200.00             0.00          200
            432002                      0.00           100.00          100
     TOTAL  432002                    200.00           100.00          100
  </code></pre>
  
  <p>After total 432 it starts to count again for total 4320001 and agian for total 432002.....
  How can i get this result? </p>
  
  <p>I'm using MS SQL SERVER 2014</p>
  
  <p><a href="http://sqlfiddle.com/#!6/ba18e" rel="nofollow">SQL FIDDLE</a></p>
  
  <p>EDIT: 
  I have tried so far this (but that is not good):</p>
  
  <pre><code> SUM(sum(column1)-sum(column2)) OVER(ORDER BY code rows UNBOUNDED PRECEDING) AS SALDO
  </code></pre>