title: Calculate difference between two timestamps in SQL in the same table
body: <p>I have a table that the columns are:</p>
  
  <pre><code>ID   UserId Serial ModifiedDate
  ---- ------ ----- ----------------
  </code></pre>
  
  <p>I need to calculate de difference between timestamp from each row. For example if i have the table like this:</p>
  
  <pre><code>ID   UserId Serial ModifiedDate
  ---- ------ ----- ----------------
  001    1     1111  2015-07-20 10:56:53.0000000
  002    1     1111  2015-07-21 18:49:24.0000000
  003    1     1111  2015-07-22 08:49:23.0000000
  </code></pre>
  
  <p>I need to make the difference between the timestamp from 001 and 002, then from 002 and 003 and the result need to be like: </p>
  
  <pre><code>ID   UserId Serial ModifiedDate                Difference 
  ---- ------ ----- ----------------             --------
  001    1     1111  2015-07-20 10:56:53.0000000 
  002    1     1111  2015-07-21 18:49:24.0000000
  003    1     1111  2015-07-22 08:49:23.0000000
  </code></pre>
  
  <p>I trying to work with cursors to do this but I couldn’t find the way to have the result of the difference in an new alias column.</p>
  
  <p>This is my query:</p>
  
  <pre><code>DECLARE @id bigint, @lastmodif datetime2(7), @id2 bigint, @lastmodif2 datetime2(7),@total int;
  
  DECLARE status_cursor CURSOR FOR 
  
  SELECT [Id], [ModifiedDate], '0' AS Difference 
  FROM [Registrations]
    where p.Serial = 1111  
    Order by ModifiedDate
  
  OPEN status_cursor
  
  DECLARE status_cursor2 CURSOR FOR 
  
  SELECT [Id], [ModifiedDate],'0' AS Difference 
  FROM [Registrations]
    where p.Serial = 1111  
    Order by ModifiedDate
  
  OPEN status_cursor2
  
  FETCH NEXT FROM status_cursor2
  
  WHILE @@FETCH_STATUS = 0
  BEGIN
  FETCH NEXT FROM status_cursor INTO @regid, @lastmodif
  FETCH NEXT FROM status_cursor2 INTO @regid2, @lastmodif2
  SET @total = 
          (
             DATEDIFF(second,@lastmodif,@lastmodif2)
          )
  UPDATE status_cursor SET Result = @total
  </code></pre>