您的位置:首页 > 数据库 > Oracle

oracle表中删除重复项的问题

2015-08-28 00:00 656 查看
摘要: 在tab_shop_info表中,删除cust_id(非主键)重复的项,只保留主键(shop_id)最小的项。

(这段是原创的)

今天心血来潮,针对前几天韩哥说的一个会员只能创建一个商铺的问题整理一下tab_shop_info这张表,然后准备删掉会员id(cust_id)重复的项,而且只留下重复项里面id(shop_id)最小的项。

T_T 本来以为两三行写完的东西,真正写起来居然这么复杂------赶紧赶紧记下来!

第一步:查询重复项;

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

第二步:查询重复项里面shop_id最小的;

select min(shop_id) from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

第三步:统计所有重复项的shop_id;

select shop_id from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

第四步:排除掉shop_id最小的那个;

select shop_if from (

select shop_id from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

)where shop_id not in(

select min(shop_id) from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

)

第五步:删除

delete from tab_shop_info where shop_id in(

select shop_if from (

select shop_id from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

)where shop_id not in(

select min(shop_id) from tab_shop_info where cust_id in (

select cust_id from tab_shop_info group by cust_id having count(cust_id) > 1

)

)

)

OK,这样才算完工了!

但是总觉得这么写好复杂啊,如果有谁写过简单一些的写法,麻烦在下面留言告知一下哈。1+1>=2,谢谢啦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  oracle 删除重复 group by