存在一张数据库表TBL1,表中有A,B两个字段,并且存在以下两个前提条件:
A是主键而且值唯一,
在实际数据中有可能有多条数据的B字段值都相同
要求:给出一个sql语句,实现可以删除表中B字段值重复的数据,当有重复发生时保留A字段值最大的那条数据;
思路:
1、//找到重复的B
select c.B from (select B from TBL1 GROUP BY B HAVING COUNT(B)>1) c
2、//找到重复的B的最大A 用函数求出来
select MAX(A) as mad from TBL1 GROUP BY B HAVING count(B)>1
3、组合删除
delete from TBL1
where B in
(select c.B from (select B from TBL1 GROUP BY B HAVING COUNT(B)>1) c)
and A not in
(select i.mad from (select MAX(A) as mad from TBL1 GROUP BY B HAVING count(B)>1) i)
转载请注明出处:
未经允许不得转载:lxfamn » sqlserver 删除重复行保留ID最大值