Delete duplicate rows from SELECT query?

扶醉桌前 提交于 2020-12-13 03:50:20

问题


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!


回答1:


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
)



回答2:


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
                 );


来源:https://stackoverflow.com/questions/64721250/delete-duplicate-rows-from-select-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!