我从此链接获得此代码:How can I remove duplicate rows?
;WITH cte
AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work, hours
ORDER BY ( SELECT 0)) RN
FROM work_hours)
DELETE FROM cte
WHERE RN > 1
是否可以删除第一个输入的重复行,或者我应该有一个额外的列date_of_entry
?我想这样做,如果我输入相同的date_work和不同的小时PARTITION BY person_id, date_work
,它会随机删除重复项。
如果不可能,我如何删除较高时间的重复项?
答案 0 :(得分:6)
添加order by hours desc
;WITH cte
AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work
ORDER BY hours DESC) RN
FROM work_hours)
DELETE FROM cte
WHERE RN > 1
答案 1 :(得分:4)
是 - 你或者必须引入date_of_entry字段或其他一些像IDENTITY
这样的矢量字段。例如,如果列Id
是您的INT IDENTITY
,那么您的查询将如下所示:
;WITH cte
AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work, hours
ORDER BY ( SELECT Id DESC)) RN
FROM work_hours)
DELETE FROM cte
WHERE RN > 1
当然如果没有人更改IDENTITY
栏中的值
如果您的条件适合 - 那么您可能希望使用列Hours
作为person_id, date_work
更好的方法就是UNIQUE INDEX
超过person_id, date_work, hours
列,然后就没有能力添加重复项了。
答案 2 :(得分:3)
您也可以使用LINQ to SQL Remove duplicates in the list using linq,带有GROUP BY http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/的SQL和SQL DISTINCT http://www.databasedev.co.uk/eliminate_duplicates.html。