Created
December 16, 2022 18:57
-
-
Save alkrauss48/1345e4ddc399fe5c9f67a5b249860ea7 to your computer and use it in GitHub Desktop.
Revisions
-
alkrauss48 created this gist
Dec 16, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,21 @@ -- DB: PostgreSQL -- Soft-delete duplicate transactions made by the same user -- of the same organization with the same amount within 3 seconds -- of the last matched transaction -- The first instance of a match will have a null time_diff, so it -- will naturally not get included in duplicate_transactions UPDATE transactions SET deleted_at = now() FROM ( SELECT id FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id, organization_id, amount ORDER BY created_at ASC) AS ordering, LAG(created_at) OVER (PARTITION BY user_id, organization_id, amount ORDER BY created_at ASC) AS last_transaction_time, created_at - LAG(created_at) OVER (PARTITION BY user_id, organization_id, amount ORDER BY created_at ASC) AS time_diff FROM transactions ) windowed_transactions where windowed_transactions.time_diff < INTERVAL '3 seconds' ) duplicate_transactions where transactions.id in (duplicate_transactions.id)