如何从SQL Server中的表中删除重复的行

时间:2013-02-27 18:49:37

标签: sql-server database

我有一个名为table1的表,它有重复的值。它看起来像这样:

new
pen
book
pen
like
book
book
pen

但我想从该表中删除重复的行,并将它们插入另一个名为table2的表中。

table2应如下所示:

new 
pen
book
like

如何在SQL Server中执行此操作?

3 个答案:

答案 0 :(得分:1)

我们假设该字段名为name

INSERT INTO table2 (name)
SELECT name FROM table1 GROUP BY name

该查询将为您提供所有唯一名称。

如果您愿意,甚至可以将它们放入表变量中:

DECLARE @Table2 TABLE (name VARCHAR(50))

INSERT INTO @Table2 (name)
SELECT name FROM table1 GROUP BY name

或者您可以使用临时表:

CREATE TABLE #Table2 (name VARCHAR(50))

INSERT INTO @Table2 (name)
SELECT name FROM table1 GROUP BY name

答案 1 :(得分:1)

您可以使用INSERT SELECT CTE轻松地执行此操作,ROW_NUMBER()使用DECLARE @YourTable table (YourColumn varchar(10)) DECLARE @YourTable2 table (YourColumn varchar(10)) INSERT INTO @YourTable VALUES ('new') INSERT INTO @YourTable VALUES ('pen') INSERT INTO @YourTable VALUES ('book') INSERT INTO @YourTable VALUES ('pen') INSERT INTO @YourTable VALUES ('like') INSERT INTO @YourTable VALUES ('book') INSERT INTO @YourTable VALUES ('book') INSERT INTO @YourTable VALUES ('pen') ;WITH OrderedResults AS ( SELECT YourColumn, ROW_NUMBER() OVER (PARTITION BY YourColumn ORDER BY YourColumn) AS RowNumber FROM @YourTable ) INSERT INTO @YourTable2 (YourColumn) SELECT YourColumn FROM OrderedResults WHERE RowNumber=1 ,例如:

YourColumn
----------
book
like
new
pen

(4 row(s) affected)

SELECT * FROM @ YourTable2

输出:

DELETE

您可以使用CTE ROW_NUMBER()轻松完成此操作,例如:

--this will just remove them from your original table
DECLARE @YourTable table (YourColumn varchar(10))
INSERT INTO @YourTable VALUES ('new')
INSERT INTO @YourTable VALUES ('pen')
INSERT INTO @YourTable VALUES ('book')
INSERT INTO @YourTable VALUES ('pen')
INSERT INTO @YourTable VALUES ('like')
INSERT INTO @YourTable VALUES ('book')
INSERT INTO @YourTable VALUES ('book')
INSERT INTO @YourTable VALUES ('pen')

;WITH OrderedResults AS
(
SELECT
    YourColumn, ROW_NUMBER() OVER (PARTITION BY YourColumn ORDER BY YourColumn) AS RowNumber
    FROM @YourTable
)
DELETE OrderedResults
    WHERE RowNumber!=1

SELECT * FROM @YourTable

输出:

YourColumn
----------
new
pen
book
like

(4 row(s) affected)

答案 2 :(得分:1)

我几周前使用DELETE TOP X发布了删除重复项的内容。显然只有一组重复项。然而在评论中,Joshua Patchak给了我一颗小宝石。

;WITH cte(rowNumber) AS
(SELECT ROW_NUMBER() OVER (PARTITION BY [List of Natural Key Fields] 
ORDER BY [List of Order By Fields]) 
FROM dbo.TableName)

DELETE FROM cte WHERE rowNumber>1

这将摆脱表格中的所有重复 如果您想阅读讨论,这是原始帖子。 Duplicate rows in a table.