我有一个名为的表table1
,其中包含重复的值。它看起来像这样:
new
pen
book
pen
like
book
book
pen
但我想从该表中删除重复的行并将它们插入另一个名为table2
.
table2
应该是这样的:
new
pen
book
like
如何在 SQL Server 中执行此操作?
我有一个名为的表table1
,其中包含重复的值。它看起来像这样:
new
pen
book
pen
like
book
book
pen
但我想从该表中删除重复的行并将它们插入另一个名为table2
.
table2
应该是这样的:
new
pen
book
like
如何在 SQL Server 中执行此操作?
您可以使用您使用INSERT
的SELECT
s轻松完成此操作,例如: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
从@YourTable2 中选择 *
输出:
YourColumn
----------
book
like
new
pen
(4 row(s) affected)
您可以在您使用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)
假设该字段名为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
几周前,我使用 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
这将消除表中的所有重复项。
如果您想阅读讨论,这是原始帖子。表中的重复行。