如何从一个SQL Server数据库表中删除重复的行?

时间:2016-09-28 08:11:46

标签: sql-server sql-server-2008

我想从一个数据库表(SQL)中删除重复的条目。 我不明白我该怎么做?

请帮我写一个问题的查询。

例如.-

Name | mobileno | address

abc  | 99xxxx01 | India

abc  | 99xxxx01 | India

def  | 98xxxx02 | USA

5 个答案:

答案 0 :(得分:2)

CREATE TABLE #Duplicate
(
    Column1 VARCHAR(5),
    Column2 VARCHAR(20),
    Column3 VARCHAR(20)
)

INSERT INTO #Duplicate VALUES('abc','99xxxx01','India'),('abc','99xxxx01','India'),('def','xxxx02','USA')

SELECT * FROM #Duplicate

;WITH CTE_Duplicate AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY Column1,Column2,Column3 ORDER BY Column1) AS Rno FROM #Duplicate
)
DELETE FROM CTE_Duplicate WHERE Rno = 2

SELECT * FROM #Duplicate

答案 1 :(得分:0)

使用公用表表达式按行复制的方式对行进行分组,并删除除其中一个之外的所有行。

请看一下这个链接:http://www.sqlservercentral.com/blogs/vivekssqlnotes/2013/12/29/deleting-duplicate-rows-using-cte/

所以你的看起来可能是这样的:

With cte_duplicate (name, mobileno, address, rownumber)
as (select name, mobileno, address, row_number()over(partition by name, mobileno, address) from your_table_name
)
delete from cte_duplicate where rownumber<>1  

答案 2 :(得分:0)

with DelCTE as
(
select Name, MobileNo, Address, row_number() over(partition by Name, MobileNo, Address order by 1) as Row_Ord
from TableName
)
delete from DelCTE
where Row_Ord >1

答案 3 :(得分:0)

;WITH numbered AS (
    SELECT ROW_NUMBER() OVER(PARTITION BY [dupe-column-list] ORDER BY [dupe-column-list]) AS _dupe_num 
    FROM [table-name] 
    WHERE 1=1 -- any where clause if required
)
DELETE FROM numbered WHERE _dupe_num > 1;

这应该会为您提供可靠的结果。

答案 4 :(得分:-2)

像这样的东西

  1. BEGIN TRAN
  2. SELECT DISTINCT * INTO #TEMP
  3. DELETE TABLE
  4. 从#TEMP
  5. 插入表格
  6. SELECT * FORM TABLE - 只需检查一切就好了
  7. - COMMIT TRAN - 如果数据一切正常,则手动执行此操作