2009-07-23 18 views
2

我想刪除基於特定列中具有相同值的副本的記錄,並保留一個被認爲是最新的記錄在我的例子下面的InsertedDate。我想要一個不使用遊標但基於設置的解決方案。目標:刪除所有重複項並保持最新狀態。根據列上的相同值刪除被認爲是重複的記錄,並保留最新

下面的ddl創建了一些重複項。需要刪除的記錄是:John1 & John2,因爲它們與John3具有相同的ID,John3是最新的記錄。

另外還記錄John5需要被刪除,因爲還有另外一個ID = 3並且更新的記錄(John6)。

Create table dbo.TestTable (ID int, InsertedDate DateTime, Name varchar(50)) 

Insert into dbo.TestTable Select 1, '07/01/2009', 'John1' 
Insert into dbo.TestTable Select 1, '07/02/2009', 'John2' 
Insert into dbo.TestTable Select 1, '07/03/2009', 'John3' 
Insert into dbo.TestTable Select 2, '07/03/2009', 'John4' 
Insert into dbo.TestTable Select 3, '07/05/2009', 'John5' 
Insert into dbo.TestTable Select 3, '07/06/2009', 'John6' 

回答

2

這工作:

delete t 
from TestTable t 
left join 
(
    select id, InsertedDate = max(InsertedDate) from TestTable 
    group by id 
) as sub on sub.id = t.id and sub.InsertedDate = t.InsertedDate 
where sub.id is null 

如果你要處理的關係它得到一點點麻煩。

+0

謝謝。在我的情況下,我不會有任何關係。我選擇了你的答案,因爲我還不熟悉SQL Server的新特性。 – 2009-07-24 06:27:56

4

只是作爲一個學術活動:

with cte as (
    select *, row_number() over (partition by ID order by InsertedDate desc) as rn 
    from TestTable) 
delete from cte 
where rn <> 1; 

大部分時間由Sam提出的解決方案執行要好得多。

+1

我更喜歡這個解決方案,因爲它處理關係,如果在綁定的情況下還有其他可能暗示保留哪個的ORDER BY,可以在某種程度上控制關係。 – 2009-07-24 00:54:36

相關問題