我如何从历史表中选择未删除的记录?

问题描述 投票:0回答:2

我有一个历史记录表表,其中保留所有记录,无论它们是插入,更新还是删除。我只想根据以下示例选择最新记录。例如,下面是两个事务23和24。我想选择23的最新更新,并想跳过24,因为它最后被删除了。请为我写一个查询。

Source:

Transaction  Flag   Date        
23            I    1/1/2020     
23            U    2/1/2020         I-Inserted
23            U    3/1/2020         U-Updated
23            U    4/1/2020         D-Deleted
24            I    1/1/2020     
24            U    2/1/2020     
24            D    3/1/2020     


Result:

Transaction  Flag      Date     
23            U    4/1/2020     
sql sql-scripts
2个回答
0
投票

一种方法使用相关子查询:

select t.*
from t
where t.date = (select max(t2.date) from t t2 where t2.transaction = t.transaction) and
      t.flag <> 'D';

0
投票

我不知道您使用的是MySQL还是SQL Server,但假设使用的是MySQL 8+或SQL Server,以下版本应该可以使用:

SELECT "Transaction", Flag, Date
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY "Transaction" ORDER BY Date DESC) rn
    FROM yourTable
) t
WHERE rn = 1 AND Flag <> 'D';
© www.soinside.com 2019 - 2024. All rights reserved.