表tb(id,orderId,type)
假设有如下记录:
1,1,NULL
2,1,01
3,2,NULL
4,2,NULL
5,2,NULL现在,要求写一条语句,删除orderId重复的记录(只保留一条),如果存在多条orderId相同的记录,最终保留下的那条是type不为NULL(如果所有的这些相同的orderId记录,type均为NULL,就随便留下一条)请问这条语句怎么写:
执行后的结果,表记录应该为:
2,1,01
3,2,NULL(当然这里的id为4或5都可以)

解决方案 »

  1.   

    SQL> delete tb where id not in ((select min(id) from tb where type is not null group by orderId)
    union(select min(id) from tb where type is null group by orderId having (orderId not in (select orderId from tb where id not in (select min(id) from tb where type is not null group by rderId)))));我表示写得很罗嗦不过貌似功能实现了。。
      

  2.   


    delete from 表tb where id not in (
     select id,orderId,type from (
       select id,orderId,type,row_number()over(partition by id order by type nulls last) rn from 表tb
     ) t where t.rn =1
    )
      

  3.   

       delete  from tb where (id,orderid,nvl(type,9)) not in( select id,orderid,nvl(type,9) from (
    select id,orderid,type,row_number() over (partition by orderid order by type,id) rn from tb) where rn=1)
      

  4.   

    delete
            from  tb a
            where a.rowid > (select min(rowid)
                               from tb t
                              where a.orderid = t.orderid
                              and   nvl(a.type, 0) = nvl(t.type, 0));
      

  5.   

    delete from 表tb where id not in (
     select id,orderId,type from (
       select id,orderId,type,row_number()over(partition by orderId order by type nulls last) rn from 表tb
     ) t where t.rn =1
    )