为什么这不能删除重复项

时间:2019-03-05 23:48:22

标签: sql sql-server database

我正在使用MySQL,但是现在我正在尝试使用MS SQL(2016)做类似的事情,但是查询无法正常工作。我有表“ TEST”,并且我正在尝试根据匹配的“姓氏,名字”列删除重复项。

使用最低的ID值:

DELETE FROM TEST
WHERE lastname NOT IN (
  SELECT t.id FROM ( 
    SELECT MIN(PersonID) id
    FROM TEST
    GROUP BY lastname, firstname
  ) t
)

这些列是:“ PersonID”“姓氏”“名字”“地址”“城市”

错误:

  

消息245,级别16,状态1,行1转换时转换失败   数据类型为int的varchar值“ JOHN”。

5 个答案:

答案 0 :(得分:1)

您要保留具有最小ID的行吗?使用EXISTS

delete t from test t
where exists (
  select 1 from test
  where firstname = t.firstname and lastname = t.lastname
  and id < t.id
)

答案 1 :(得分:1)

您正在将姓氏与ID进行比较,因此报告了错误“将varchar值'JOHN'转换为数据类型int时转换失败” ,请尝试以下操作:

DELETE FROM TEST
WHERE PersonID NOT IN (
  SELECT t.id FROM ( 
    SELECT MIN(PersonID) id
    FROM TEST
    GROUP BY lastname, firstname
  ) t
)

答案 2 :(得分:0)

在SQL Server中,我建议为此使用窗口函数:

with todelete as (
      select t.*,
             row_number() over (partition by firstname, lastname order by id) as seqnum
      from test t
     ) 
delete from todelete
    where seqnum > 1;

答案 3 :(得分:0)

由于lastname是字符,因此您可以尝试将ID转换为varchar / nvarchar。尽管您可能会再次检查是否应引用PersonID或姓氏。

DELETE FROM TEST
WHERE lastname NOT IN (
  SELECT CONVERT(VARCHAR(50),t.id) FROM ( 
    SELECT MIN(PersonID) id
    FROM TEST
    GROUP BY lastname, firstname
  ) t
)

答案 4 :(得分:0)

您也可以尝试这种方法:

DELETE T2 FROM ( 
    SELECT 
        MIN(PersonID) id
    FROM 
        TEST
    GROUP BY 
        lastname, firstname
  ) t
INNER JOIN TEST T2 ON t.id = T2.PersonID