删除双项

时间:2017-01-25 13:19:04

标签: sql-server tsql sql-server-2016

我遇到的问题是,在一张桌子上它有时会进行双重输入。我想删除doubled条目。我只想在两个值都与另一行相同时删除一行。这怎么可能?

我的数据库结构:

enter image description here

双重条目的示例:

enter image description here

1 个答案:

答案 0 :(得分:1)

一种方法是使用exists:

DELETE t0
FROM Password_Department t0
WHERE EXISTS
(
    SELECT 1
    FROM Password_Department t1
    WHERE t0.PasswordFK = t1.PasswordFK
    AND t0.DepartmentFK = t1.DepartmentFK
    AND t0.Id > t1.Id
)

如果您更喜欢行号方法 -

delete x 
from (
   select *, 
          rn = row_number() over (partition by DepartmentFK, PasswordFK order by Id)
   from Password_Department 
) x
where rn > 1

删除重复条目后,应在PasswordFK和DepartmentFK上添加唯一约束:

ALTER TABLE Password_Department 
ADD Constraint UC_Password_Department UNIQUE (PasswordFK , DepartmentFK)