我有一个重复的表事务。我想保留具有最小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)
答案 0 :(得分:3)
执行类似
的操作可能更有效率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 )
答案 1 :(得分:1)
DELETE FROM transaction
WHERE ID IN (
SELECT ID
FROM (SELECT ID,
ROW_NUMBER () OVER (PARTITION BY date
,amount
,refnumber
,parentfolderid
ORDER BY ID) rn
FROM transaction)
WHERE rn <> 1);
我会这样尝试
答案 2 :(得分:0)
我会尝试这样的事情:
DELETE transaction
FROM transaction
LEFT OUTER JOIN
(
SELECT MIN(id) as id, date, amount, refnumber, parentfolderid
FROM transaction
GROUP BY date, amount, refnumber, parentfolderid
) as validRows
ON transaction.id = validRows.id
WHERE validRows.id IS NULL