问题
I am trying to delete some duplicates out of a table and trying to retain one of the duplicates for ID1 column.
Using this query I managed to delete based on ROWID.
delete from tabela.lorik
where ROWID not in (
select MAX(ROWID)
from tabela.lorik
GROUP BY ID1)
Now I want to delete all those records found duplicate where NETAMT = 0
回答1:
You can achieve this using the following query:
delete from tabela.lorik O
where O.netamt = 0
AND EXISTS (SELECT 1 FROM tabela.lorik I
WHERE I.ID = O.ID AND I.netamt <> 0)
I am assuming that you need to delete only records where it is netamount = 0
, If not then do comment below.
If you are looking to retain one non-zero entry and delete all others(In case of all the zeros, one entry with zero as netamount
will be retained) then you can use the following query:
DELETE FROM TABELA.LORIK O
WHERE
ROWID IN (
SELECT
RWID
FROM
(
SELECT
ROWID AS RWID,
ROW_NUMBER() OVER(
PARTITION BY ID
ORDER BY
CASE
WHEN NETAMT = 0 THEN 2
ELSE 1
END
) AS RN
FROM
TABELA.LORIK
)
WHERE
RN > 1
);
Cheers!!
回答2:
You can order the rowid
s by the value first and then rowid
. This following keeps only one row, with a preference for the most recent non-zero amount:
delete from tabela.lorik
where ROWID <> (select max(rowid) keep (dense_rank first (order by (case when amount = 0 then 1 else 2 end), rowid desc)
from tabela.lorik l2
where l2.id1 = l.id1
)
来源:https://stackoverflow.com/questions/58485689/oracle-deleting-duplicates-based-on-a-condition