删除重复记录
各位大虾,想从表TB中删除重复次数最少的记录,重复次数最少的记录有很多条,比如
10,20,30
11,12,13
21,22,23
24,25,26
假如上面4条记录都重复了3次,是重复次数最少的,想一次把它们全删除可用下面的命令只能删除一条,请大虾们帮忙。
DELETE a FROM TB a INNER JOIN
(SELECT TOP 1 e,f,g,COUNT(*) c FROM TB GROUP BY e,f,g ORDER BY COUNT(*) ASC) b ON
a.e=b.e AND a.f=b.f AND a.g=b.g
[解决办法]
先不管写法,我想知道如果真有3条重复的,为什么只删除一条而不只保留一条呢?这样从业务上貌似说不过去
[解决办法]
删除重复的容易,问题是为什么只删除"重复次数最少的,而不全部删除"
[解决办法]
create table #t
(
A int,
B int,
C int
)
insert into #t
select 1,1,1 union all
select 1,2,0 union all
select 1,3,1 union all
select 1,4,0
select * from #t
union all
select * from #t where C = 0
order by B,C
INSERT INTO #t SELECT * FROM #t where C=0
SELECT COUNT(*) as co,A,B,C into #t2 FROM #t GROUP BY A,B,C ORDER BY COUNT(*)
SELECT a,b,c into #t3 FROM #t2 WHERE co=(SELECT MIN(co) from #t2)
DELETE a FROM #t a INNER JOIN #t3 b ON a.A=b.A and a.B=b.B and a.c=b.c