title: How to combine two closest rows into one row based on the created timestamp
body: <p>I have the following sql 2008 table. </p>
  
  <pre><code>ID  RefundId    RefundStatusId          CreatedOn
  334 549         3                   2011-10-12 12:04:37.773
  333 549         1                   2011-10-12 12:04:20.390
  332 549         6                   2011-10-12 12:03:05.990
  </code></pre>
  
  <p>Any query can give me a result like: </p>
  
  <pre><code>RefundCheckId   StatusId             PreviousStatusId           CreatedOn
      549             3                    1                        2011-10-12 12:04:37.773
      549             1                    6                        2011-10-12 12:04:20.390
      549             6                    null                     2011-10-12 12:03:05.990
  </code></pre>
  
  <p><strong>Solution below : Updated based on Marco's answer.</strong></p>
  
  <pre><code>SELECT t.RefundId AS RefundCheckId, t.RefundStatusId AS StatusId,
    (SELECT TOP 1 RefundStatusId FROM table
     WHERE RefundId = t.RefundId AND CreatedOn &lt; t.CreatedOn
     ORDER BY CreatedOn DESC) AS PreviousStatusId, t.CreatedOn
  FROM table t
  WHERE t.RefundId = 549
  ORDER BY t.CreatedOn DESC
  </code></pre>