title: SQL. DateDiff between rows under conditions determined by parsing row contents
body: <p>I have a set of data that goes sort of like:</p>
  
  <pre><code>TimeStamp    | Action
  -------------+-------------------------
  '2016-01-01' | 'State changed to 1'
  '2016-01-03' | 'State changed to 2'
  '2016-01-07' | 'State changed to 1'
  '2016-01-12' | 'State changed to 2'
  '2016-01-20' | 'State changed to Final'
  </code></pre>
  
  <p>What I need to count is how much time have the object spent in the state '1', how much time it spent in state '2', etc.</p>
  
  <p>I can't wrap my head around how to play with DateDiff in order to have output like (considering we counting how many <em>days</em> each of the states last):</p>
  
  <pre><code>'1' | '2'
  ---------
    5 | 12
  </code></pre>
  
  <p>So I generally have two questions:</p>
  
  <ol>
  <li>Is it even possible to do that with SQL?</li>
  <li>If it is - how can that be done?</li>
  </ol>
  
  <p>Thanks in advance!</p>
  
  <p>Edit: forgot to mention DBMS is SQL Server 2012.</p>