假设我的表中有重复的行,而且我的数据库设计是第3类: –
Insert Into tblProduct (ProductId,ProductName,Description,Category) Values (1,'Cinthol','cosmetic soap','soap'); Insert Into tblProduct (ProductId,'Lux','Crowning Glory',Category) Values (2,'nice soap',Category) Values (3,'soap');
我希望每个表中只有1个实例存在于我的表中.因此,应删除第2行,第3行和最后一行完全相同的行.我可以为此写什么查询?可以在不创建临时表的情况下完成吗?只需一个查询?
提前致谢 :)
解决方法
试试这个 – 它将删除表中的所有重复项:
;WITH duplicates AS ( SELECT ProductID,Category,ROW_NUMBER() OVER (PARTITION BY ProductID,ProductName ORDER BY ProductID) 'RowNum' FROM dbo.tblProduct ) DELETE FROM duplicates WHERE RowNum > 1 GO SELECT * FROM dbo.tblProduct GO
您的副本现在应该消失了:输出是:
ProductID ProductName DESCRIPTION Category 1 Cinthol cosmetic soap soap 1 Lux cosmetic soap soap 1 Crowning Glory cosmetic soap soap 2 Cinthol nice soap soap 3 Lux nice soap soap