I have the following sql 2008 table.
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
Any query can give me a result like:
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
Solution below : Updated based on Marco’s answer.
SELECT t.RefundId AS RefundCheckId, t.RefundStatusId AS StatusId,
(SELECT TOP 1 RefundStatusId FROM table
WHERE RefundId = t.RefundId AND CreatedOn < t.CreatedOn
ORDER BY CreatedOn DESC) AS PreviousStatusId, t.CreatedOn
FROM table t
WHERE t.RefundId = 549
ORDER BY t.CreatedOn DESC
Try
MySql version
MS-SQL version