正在从 SQL 服务器 table 中删除重复项

Removing duplicates from SQL Server table

我的 SQL 服务器 table 有很多重复的记录,如下所示:

 SID    Username                                InQueue
------------------------------------------------------------------    
 162    peeeer2  492    2017-01-18 12:20:21.820   0    354
2791    peeeer2  460    2017-01-11 00:00:00.000   1    NULL

这里不需要的记录是我设置的peeeer2用户InQueue = true。我需要删除所有那些 InQueue 列设置为 1 的重复项,另一个条件是用户名实际上是重复项...

table 名字是 SearchedUsernames:

delete from SearchedUsernames
where Username ??

有人可以帮我解决这个问题吗?

编辑:

@TimSchmelter 非常喜欢,这很有魅力。但是我仍然收到错误消息。我需要先删除此 table 的相邻 FK。例如,当我在邻近 table 中有一个相应的 FK 记录时,称为 UserTransactions,如下所示:

 ID      SID                              
----------------  
 162    162
2791    2791    

我需要先删除这个相邻 table 中的所有记录,然后使用您编写的查询删除重复项。但是,这次我只想删除那些具有重复记录并已设置 InQueue = 0 的记录;

所以场景看起来像这样:

  1. 从相邻 table UserTransactions

  2. 中的两个副本中删除 FK 记录 SID
  3. 然后执行 DTV & Tim 编写的查询,稍作改动,只删除那些重复的记录并设置 InQueue = 0;

WITH cte AS (
    SELECT Username, inqueue,
        ROW_NUMBER() OVER (PARTITION BY Username ORDER BY InQueue ASC) AS RN
    FROM searchedUsernames   
)
DELETE FROM cte
WHERE RN > 1;

如果怕超过一个Inqueue=0,那就用RANK

WITH cte AS (
    SELECT Username, inqueue,
        RANK() OVER (PARTITION BY Username ORDER BY InQueue ASC) AS RN
    FROM searchedUsernames   
)
DELETE FROM cte
WHERE RN > 1;

您可以像这样使用自连接:

 DELETE t0
 FROM SearchedUsernames t0
 INNER JOIN SearchedUsernames t1 ON(t0.Username = t1.Username AND t0.IsQueue <> T1.IsQueue)
 WHERE AND t0.IsQueue = 1

可能最直观的解决方案是:

delete s from SearchedUsernames s
where InQueue = 1 and exists(select * from SearchedUsernames
                             where InQueue = 0 and Username = s.Username)