Since there can be peers sharing the same maximum quantity, the safe route is a subquery with the window function row_number()
:
DELETE FROM transaction t
USING (
SELECT some_unique_id, row_number() OVER (PARTITION BY item_name
ORDER BY quantity DESC) AS rn
FROM transaction
GROUP BY 1
) sub
WHERE t.some_unique_id = sub.some_unique_id
AND sub.rn > 1;
Where some_unique_id
can be any unique column or combination of columns (mirrored in the GROUP BY
clause).
Ends up to be very similar to this question from today:
Delete rows with duplicates on two fields
If your table is big and you are going to delete large parts of it, consider advanced advice here:
How to delete duplicate entries?