4

这是我表中的列:

Id
EmployeeId
IncidentRecordedById
DateOfIncident
Comments
TypeId
Description
IsAttenIncident

我想删除相同的重复行EmployeeId, DateOfIncident, TypeId-Description只是为了澄清 - 我确实想保留其中之一。我想我应该使用OVERwith 子句PARTITION,但我不确定。

谢谢

4

3 回答 3

18

如果您想保留一行重复组,您可以使用ROW_NUMBER. 在此示例中,我保留最低的行Id

WITH CTE AS 
(
    SELECT rn = ROW_NUMBER() 
                OVER( 
                  PARTITION BY employeeid, dateofincident, typeid, description 
                  ORDER BY Id ASC), * 
    FROM dbo.TableName
) 
DELETE FROM cte 
WHERE  rn > 1 
于 2013-04-24T15:22:14.577 回答
2

在不使用 CTE 的情况下使用此查询....

从 (select id,name,place, ROW_NUMBER() over (partition by id,name,place order by id) row_Count from dup_table) 删除 a where a.row_Count >1

于 2013-11-21T12:04:24.797 回答
0

您可以使用以下查询。这假设您要保留最新行并删除其他重复项。

DELETE [YourTable]
FROM [YourTable]  
LEFT OUTER JOIN (  
   SELECT MAX(ID) as RowId 
   FROM [YourTable]   
   GROUP BY EmployeeId, DateOfIncident, TypeId, Description  
) as KeepRows ON  
   [YourTable].ID = KeepRows.RowId  
WHERE  
   KeepRows.RowId IS NULL
于 2013-08-02T10:08:29.790 回答