我有以下sql 2008表。
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
任何查询都可以给我一个结果:
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
以下解决方案:根据Marco的回答进行了更新。
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
答案 0 :(得分:3)
尝试
SELECT t.RefundId AS RefundCheckId, t.RefundStatusId AS StatusId,
(SELECT RefundStatusId FROM your_table
WHERE ID < t.ID
ORDER BY ID DESC
LIMIT 1) AS PreviousStatusId, t.CreatedOn
FROM your_table t
ORDER BY t.ID DESC
SELECT t.RefundId AS RefundCheckId, t.RefundStatusId AS StatusId,
(SELECT TOP 1 RefundStatusId FROM your_table
WHERE ID < t.ID
ORDER BY ID DESC) AS PreviousStatusId, t.CreatedOn
FROM your_table t
ORDER BY t.ID DESC