title: How to get the difference in dates in SQL Server
body: <p>I'm having trouble with writing a query to get difference between the UpdateDate and the CreationDate of 2 records if the ID is the lowets and the difference between the most recent and second most recent UpdateDate.
  Here's my Query:</p>
  
  <pre><code>SELECT 
      a.ID, a.RequestID, b.KrStatus, b.CrDate , b.UpdateDate, 
      DATEDIFF (HOUR, b.CrDate, b.UpdateDate) AS TimeDifference,
  CASE WHEN a.ID = (SELECT MAX(a.ID) FROM [dbo].[Krdocs_hist] a WHERE a.RequestID = 1)
      THEN 'YES'
      ELSE 'NO'
  END AS isMax,
  CASE WHEN a.ID = (SELECT MIN(a.ID) FROM [dbo].[Krdocs_hist] a WHERE a.RequestID = 1)
      THEN 'YES'
      ELSE 'NO'
  END AS isMi
  FROM [dbo].[Krdocs_hist] a, [dbo].Krdocs_Details_hist b
  WHERE 
      a.RequestId = b.RequestId
      and a.ID = b.ID 
      and a.RequestId = 1
  ORDER BY b.RequestID
  </code></pre>
  
  <p>Here's my current result:
  <a href="https://i.stack.imgur.com/CAkcz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CAkcz.png" alt="enter image description here"></a></p>
  
  <p>What I'd like to do is get the last possible record, check to see if there was an existing one before it. If there wasn't compare the UpdateDate and CrDate (UpdateDate minus CrDate. If there was a record before this I want to do the UpdateDate minus the previous UpdateDate.</p>
  
  <p>Using this query:</p>
  
  <pre><code>SELECT b.Id, b.RequestId, b.UpdateDate, b.KrStatus
  FROM [dbo].[Krdocs_Details_hist] b
  WHERE b.RequestId = 1
  </code></pre>
  
  <p>Has this result:
  <a href="https://i.stack.imgur.com/f03kU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f03kU.png" alt="enter image description here"></a></p>
  
  <p>And using this query:</p>
  
  <pre><code>SELECT a.*
  FROM [dbo].[Krdocs_hist] a
  WHERE RequestId = 1
  </code></pre>
  
  <p>Has this result:
  <a href="https://i.stack.imgur.com/KZnzB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KZnzB.png" alt="enter image description here"></a></p>