用于计算重复项的SQL查询


SQL query to count duplicates

本问题已经有最佳答案,请猛点这里访问。

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


我同意所有意见,请参阅如何询问

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

1
2
3
4
5
6
7
8
9
  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;

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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