Eliminare le righe duplicate dalla query SELECT?
Sto lavorando con SQLite e attualmente sto tentando di eliminare alcune righe duplicate da un determinato utente (con ID 12345). Sono riuscito a identificare tutte le righe che desidero eliminare, ma ora non sono sicuro di come procedere per eliminare queste righe. Questa è la mia SELECTdomanda:
SELECT t.*
from (select t.*, count(*) over (partition by code, version)
as cnt from t) t
where cnt >= 2 and userID = "12345";
Come dovrei eliminare le righe corrispondenti a questo risultato? Posso utilizzare la query precedente in qualche modo per identificare le righe che voglio eliminare? Grazie in anticipo!
Risposte
Puoi ottenere tutte le code, versioncombinazioni duplicate per userid = '12345'con questa query:
select code, version
from tablename
where userid = '12345'
group by code, version
having count(*) > 1
e puoi usarlo DELETEnell'istruzione:
delete from tablename
where userid = '12345'
and (code, version) in (
select code, version
from tablename
where userid = tablename.userid
group by code, version
having count(*) > 1
)
Se vuoi mantenere 1 delle righe duplicate, usa la MIN()funzione finestra per ottenere la riga con il min rowidper ogni combinazione di code, versioned escluderla dall'eliminazione:
delete from tablename
where userid = '12345'
and rowid not in (
select distinct min(rowid) over (partition by code, version)
from tablename
where userid = tablename.userid
)
Hmmm. . . non devi usare le funzioni della finestra:
delete from t
where exists (select 1
from t t2
where t2.code = t.code and t2.version = t.version
group by code, version
having count(*) >= 2
);