![](/img/trans.png)
[英]Why xmax system column in postgres table is not zero for non-deleted row?
[英]How do I select non-deleted records from a history table?
我有一個歷史記錄表,我在其中保存所有記錄,無論它們是插入、更新還是刪除。 我只想 select 按照下面的示例獲取最新記錄。 例如,下面是兩個事務 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
一種方法使用相關子查詢:
select t.*
from t
where t.date = (select max(t2.date) from t t2 where t2.transaction = t.transaction) and
t.flag <> 'D';
I don't know whether you are using MySQL or SQL Server, but assuming MySQL 8+ or SQL Server, here is a version which should work:
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';
演示在 SQL 服務器中,但基本代碼應在任何支持ROW_NUMBER
的數據庫上運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.