【Stackoverflow好问题】SQL中去除重复行

2015-01-25 19:54:25 · 作者: · 浏览: 6
问题 假设有一个数据量比较大的表(例如300,000+行),其中有重复的行(除了主键外,其他的列数据是一样的),如何快速去重呢? 我的表类似这样
MyTable
-----------
RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null

精华回答 假设没有null值,你可以先对其他列做group by,然后只保留MIN或者MAX(RowId),删除其他行:
DELETE MyTable FROM MyTable LEFT OUTER JOIN ( SELECT MIN(RowId) as RowId, Col1, Col2, Col3 FROM MyTable GROUP BY Col1, Col2, Col3 ) as KeepRows ON MyTable.RowId = KeepRows.RowId WHERE KeepRows.RowId IS NULL
如果RowId不是int类型,而是个GUID,则可以用
CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))