小编典典

SQL删除表中的重复项

sql

我有一个重复的表事务。我想保留具有最小id的记录,并基于四个字段DATE,AMOUNT,REFNUMBER,PARENTFOLDERID删除所有重复项。我写了这个查询,但是我不确定这是否可以有效地编写。您认为有更好的方法吗?我问是因为我担心运行时间。

DELETE FROM TRANSACTION
WHERE ID IN 
(SELECT FIT2.ID
FROM
(SELECT MIN(ID) AS ID, FIT.DATE, FIT.AMOUNT, FIT.REFNUMBER, FIT.PARENTFOLDERID
FROM EWORK.TRANSACTION FIT
GROUP BY FIT.DATE, FIT.AMOUNT , FIT.REFNUMBER, FIT.PARENTFOLDERID
HAVING COUNT(1)>1 and FIT.AMOUNT >0) FIT1,
EWORK.TRANSACTION FIT2

WHERE FIT1.DATE=FIT2.DATE AND
FIT1.AMOUNT=FIT2.AMOUNT AND
FIT1.REFNUMBER=FIT2.REFNUMBER AND 
FIT1.PARENTFOLDERID=FIT2.PARENTFOLDERID AND 
FIT1.ID<>FIT2.ID)

阅读 231

收藏
2021-04-07

共1个答案

小编典典

做这样的事情可能会更有效

DELETE FROM transaction t1
 WHERE EXISTS( SELECT 1
                 FROM transaction t2
                WHERE t1.date = t2.date
                  AND t1.refnumber = t2.refnumber
                  AND t1.parentFolderId = t2.parentFolderId
                  AND t2.id > t1.id )
2021-04-07