用于计算重复项的SQL查询

时间:2017-05-11 14:26:21

标签: sql

请协助我查询重复计数和查询以删除重复项。

1 个答案:

答案 0 :(得分:1)

我同意所有评论,请参阅How To Ask

在这个机会中,这对你有用,并且为了它对我自己而言是一个很好的练习,它帮助其他人偶然发现这个,这里有一些GENERIC代码可以做到:

  WITH CTE AS
  (
    SELECT 
    COALESCE(Col1,'') AS Col1, 
    COALESCE(Col2,'') AS Col2, ROW_NUMBER() OVER(PARTITION BY col1,col2 ORDER BY col1,col2) AS row_id
    FROM MyTable
  )

DELETE CTE WHERE row_id >1;

示例:

Create table #things (FirstName varchar(10), LastName varchar(10))
insert into #things (FirstName, LastName) 
values('thing','lastthing'),('thing','lastthing'),('otherthing', 'something')

select * from #things

  ;WITH CTE AS
  (
    SELECT 
    COALESCE(firstname,'') AS Col1, 
    COALESCE(lastname,'') AS Col2, ROW_NUMBER() OVER(PARTITION BY firstname,lastname ORDER BY firstname,lastname) AS row_id
    FROM #things
  )

DELETE CTE WHERE row_id >1;

select * from #things

drop table #things