面试题中经常遇到的SQL题:删除重复数据,保留其中一条
如题,解决思路如下:
1、首先我们需要找出拥有重复数据的记录
1 ---以name字段分组 2 select Name,COUNT(Name) as [count] from Permission group by Name-- having COUNT(Name)>1 3 4 ---以name字段分组,筛选出有重复出现的字段 having 用于条件筛选 作用相当于where 区别where用于group by 之前,having用于之后 5 select Name,COUNT(Name) as [count] from Permission group by Name having COUNT(Name)>1
执行结果:
2、然后我们需要知道要要保留的记录的ID号,或者其他唯一标识字段
1 ---获取重复记录中最小的一项的ID号 2 select min(ID),Name,COUNT(Name) as [count] from Permission group by Name having COUNT(Name)>1
执行结果:
3、组合前面两个数据查询条件,进行删除操作
1 ---删除重复数据 2 delete from Permission 3 ---找出拥有相同数据的记录 4 where Name in (select Name from Permission group by Name having COUNT(Name)>1) 5 ---除了最小ID号的数据保留,其他的删除 (也可以用max(id)) 6 and ID not in (select min(ID) from Permission group by Name having COUNT(Name)>1)
漫漫人生,唯有激流勇进,不畏艰险,奋力拼搏,方能中流击水,抵达光明的彼岸