回答

收藏

根据列上的相同值删除被视为重复的记录,并保持最新记录

技术问答 技术问答 112 人阅读 | 0 人回复 | 2023-09-13

我想删除在某些列中基于相同值的被视为重复的记录,并在下面的示例中保留一个基于InsertedDate的最新记录。我想要一个不使用游标而是基于设置的解决方案。目标:删除所有重复项并保持最新。% A# s* A+ N' w' f, M5 |
下面的ddl创建了一些重复项。需要删除的记录为:John1和John2,因为它们具有与John3相同的ID,而John3是最新的记录。
5 \" {5 m/ v- B6 P  X+ o6 _8 c另外,需要删除记录John5,因为还有另一条ID = 3且较新的记录(John6)。2 O  m7 L9 |" I5 c. r, C: A; g
Create table dbo.TestTable (ID int, InsertedDate DateTime, Name varchar(50))
; \- k( U; J" R, @/ ]6 o# u$ tInsert into dbo.TestTable Select 1, '07/01/2009', 'John1'" u* j/ f- J5 E7 v: i
Insert into dbo.TestTable Select 1, '07/02/2009', 'John2'2 D9 m; i- Z7 ?/ \" `
Insert into dbo.TestTable Select 1, '07/03/2009', 'John3'; K+ [! Q* x1 g8 p- h$ S: m
Insert into dbo.TestTable Select 2, '07/03/2009', 'John4'
+ j: }1 E& C! \  C# YInsert into dbo.TestTable Select 3, '07/05/2009', 'John5'
' G0 J' c1 k/ r! BInsert into dbo.TestTable Select 3, '07/06/2009', 'John6'- c- J; @- S2 |+ z% _# u
                5 |$ X' h2 r4 I
解决方案:
7 y) H, ]0 v6 I5 ]! o) Y5 g                $ x7 X9 E. S" ^8 A2 J/ E
' {. x" p$ S9 j; Z+ o. {3 E: T0 ^
! J! D2 @$ G/ ~% W
                这有效:4 Y, D8 D' P) H  \6 }& ]% C* }9 k
delete t
" }  e) [1 R# \5 q, X- w) Z& z" sfrom TestTable t4 A# b) q$ o4 D5 M! c
left join
5 u6 w& b" S7 }( K9 |! T: m) J(7 U& `0 V' Q  s+ u9 I  b! O! m* ?
    select id, InsertedDate = max(InsertedDate) from TestTable
  E) I& n) R; r    group by id2 e# P4 o4 c  S6 K5 ?  Y
) as sub on sub.id = t.id and sub.InsertedDate = t.InsertedDate) k. a, o/ z! Y; I( L9 ^
where sub.id is null0 B  K% I# {) v* Z- s! Y
如果您必须处理领带,那会有些棘手。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则