Reputation: 591
I'm working with SQLite and currently attempting to delete certain duplicate rows from a certain user (with ID 12345). I've managed to identify all of the rows I wish to delete, but I'm now unsure how to go about deleting these rows. This is my SELECT
query:
SELECT t.*
from (select t.*, count(*) over (partition by code, version)
as cnt from t) t
where cnt >= 2 and userID = "12345";
How would I go about deleting the rows matching this result? Can I use the query above in some way to identify which rows I want to delete? Thanks in advance!
Upvotes: 1
Views: 87
Reputation: 164064
You can get all the duplicate code, version
combinations for userid = '12345'
with this query:
select code, version
from tablename
where userid = '12345'
group by code, version
having count(*) > 1
and you can use it in the DELETE
statement:
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
)
If you want to keep 1 of the duplicate rows, use MIN()
window function to get the row with the min rowid
for each combination of code, version
and exclude it from being deleted:
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
)
Upvotes: 1
Reputation: 1269463
Hmmm . . . you don't have to use window functions:
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
);
Upvotes: 0