从sql中的表中删除几个重复的行

时间:2017-05-26 02:48:12

标签: sql sql-server

我得到了大约5个用户的列表,这些用户在表格中有重复的条目。 这是我用来获取重复条目的查询。请建议删除一些条目的简单方法。

USE [DB]

SELECT UserName, COUNT(*) AS CountOF 
FROM UserDetails
WHERE RoleID = '2'
GROUP BY UserName
HAVING COUNT(*) > 1

2 个答案:

答案 0 :(得分:3)

使用方括号表示SQL Server。如果是这样,你可以这样做:

WITH todelete as (
      SELECT ud.*,
             ROW_NUMBER() OVER (PARTITION BY RoleId, username ORDER BY RoleId) as seqnum
      FROM UserDetails
      WHERE RoleID = 2
     )
DELETE FROM todelete
    WHERE seqnum > 1;

注意:如果RoleId是数字,则不要将该值与字符串进行比较。

答案 1 :(得分:0)

需要另一个uniq列,如id或createtime 更多数据库支持

with repeatData as (
    SELECT UserName,COUNT(*) as CountOF,min(id) as keepTag FROM UserDetails
    WHERE RoleID = '2'
    GROUP BY UserName
    HAVING COUNT(*)>1),
toDelData as (
    select id from UserDetails 
    where UserName in (SELECT UserName from repeatData) 
    and id not in (SELECT keepTag from repeatData) )
delete FROM UserDetails where id in (select id from toDelData )