如何删除具有一个唯一列的重复记录

时间:2015-02-13 08:04:19

标签: sql sql-server duplicate-removal

我有一张这样的桌子。

enter image description here

如何删除具有更大月值的记录“Jimmy”和“Kenneth”。

谢谢。

5 个答案:

答案 0 :(得分:4)

使用CTE删除重复记录

;with cte as
(
select Rn=row_number()over(partition by name,post order by month ASC),* 
from yourtable 
)
delete from cte where rn>1

答案 1 :(得分:2)

如果月份是一列数字,请尝试:

DELETE table
WHERE  month = (SELECT Max(month)
                FROM   table
                WHERE  name = 'Jimmy')
       AND name = 'Jimmy';

DELETE table
WHERE  month = (SELECT Max(month)
                FROM   table
                WHERE  name = 'Kenneth')
       AND name = 'Kenneth'; 

答案 2 :(得分:1)

delete from tablename t1 where exists (select 1 from tablename t2
                                       where t1.name = t2.name
                                         and t1.month > t2.month)

但为什么不考虑一年?为什么不使用日期数据类型? 如果同月有两个Jimmys怎么办? 如果不允许重复,为什么没有唯一约束?

答案 3 :(得分:1)

您可以使用over partition来分隔Month中的最大值:

SELECT *
FROM   (SELECT *,
               Row_number()OVER(PARTITION BY name, Post
                   ORDER BY Month DESC) AS RowNumber
        FROM   TABLE)
WHERE  rownumber = 1 

答案 4 :(得分:0)

使用此代码..

WITH tblTemp as(SELECT ROW_NUMBER() Over(PARTITION BY Name,Post ORDER BY Name)As RowNumber,* FROM <table_name>)DELETE FROM tblTemp where RowNumber >1