oracle表中删除重复项的问题

(这段是原创的)

今天心血来潮,针对前几天韩哥说的一个会员只能创建一个商铺的问题整理一下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,by,group,删除重复)