继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

sql server 删除重复的数据

诡异之心0908
关注TA
已关注
手记 9
粉丝 16
获赞 1027

1--删除name,sex重复的数据,只留下一条数据;

select * into #lin1 from student   --先将student的数据插入临时表#lin1中;
select min(id) as iidd into #lin2 from student group by name,sex   --根据name,sex分组,并获取每组中最小的id;
select * from student where id not in(select iidd from #lin2)      --确认查询出的这些数据,是否是重复的并且可以删除的数据;
delete student where id not in(select iidd from #lin2)             --确认无误后,删除重复的数据;
select * from student                                              --查看数据;

insert into student select * from #lin1     --删除后又想回复删除前的数据时,执行这条语句;
drop table #lin1        
drop table #lin2                            --最后删除这两张临时表;

2--只删除一个字段(name)的重复数据时;


select min(id) from student group by name
delete student where id not in (select min(id) from student group by name)

将删除语句整合成一条:

DELETE a FROM student AS a  JOIN (SELECT name,COUNT(*) AS num,MAX(id) FROM student GROUP BY name HAVING COUNT(*)>1) AS b ON a.name=b.name WHERE a.id<b.id;
打开App,阅读手记
10人推荐
发表评论
随时随地看视频慕课网APP