0

I have a history table table where i keep all the records whether they are inserted, updated or deleted. I want to select only the latest record as per below example. Example, Below are two transactions 23 and 24. I want to pick the latest update of 23 and want to skip 24 because it is deleted at the end. Please write a query for me.

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     
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
John Bristiw
  • 27
  • 1
  • 1
  • 7

2 Answers2

0

One method uses correlated subqueries:

select t.*
from t
where t.date = (select max(t2.date) from t t2 where t2.transaction = t.transaction) and
      t.flag <> 'D';
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

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';

Demo

The demo is in SQL Server, but the basic code should run on any database which supports ROW_NUMBER.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360