zoukankan      html  css  js  c++  java
  • oracle 查询及删除表中重复数据

    create table test1(
    id number,
    name varchar2(20)
    );
    

      

    insert into test1 values(1,'jack');
    insert into test1 values(2,'jack');
    insert into test1 values(3,'peter');
    insert into test1 values(4,'red');

     insert into test1 values(5,'green');
      insert into test1 values(6,'green');

    一 查询表中重复数据

     1. 使用exists

     1 select a.* from test1 a
     2 
     3 where exists
     4 
     5 ( 
     6     select name from 
     7         ( select name ,count(*) 
     8                     from test1 
     9                         group by name 
    10                            having count(*)>1
    11          ) b 
    12       where a.name = b.name
    13 );                

    2 join on

    select a. * from test1 a 
        join (
                  select name ,count(*) from test1
                       group  by name 
                              having count(*)>1
              ) b
       on a.name = b.name;            

    3 in

    select a.name from test1 a 
        where a.name in 
              (
                select name  from test1  
                    group  by name 
                       having   count(*)>1
              );    

     

    4 使用rowid 查询得到重复记录里,第一条插入记录后面的记录

    select * from test1 a where  rowid != (select min(rowid) from test1 b where b.name = a.name);
    

      

    5 使用rowid查询得到重复记录里,最后一条记录之前插入的记录

    select a.* from test1 a where rowid !=(select max(rowid) from test1 b where a.name=b.name);
    

      

    6 使用rowid 查询得到 不重复的记录和重复记录里最后插入的一条记录

    select a.* from test1 a where rowid =(select max(rowid) from test1 b where a.name=b.name);
    

      

    7 使用rowid 查询得到不重复的记录和重复记录里最先插入的记录

    select * from test1 a where  rowid = (select min(rowid) from test1 b where b.name = a.name);
    

      

     删除  所有重复不保留任何一条

    delete  from test1 a where exists ( select name from (select name ,count(*) from test1  group  by name having count(*)>1) b where a.name = b.name);
    

      

    delete from test1 a where a.name in (select name  from test1  group  by name having count(*)>1);
    

      

     删除重复记录里,第一条重复记录后面插入的记录

    delete from test1 a where  rowid  !=(select min(rowid) from test1 b where b.name = a.name);
    

      

    删除先前插入的重复记录,保留最后插入的重复记录

    delete  from test1 a where rowid !=(select max(rowid) from test1 b where a.name=b.name);
    

      

  • 相关阅读:
    android socket传输序列化对象的代码
    python通过pil模块对图片格式进行转换的代码
    python获取命令行参数的代码
    【LEETCODE】41、905. Sort Array By Parity
    【LEETCODE】40、1051. Height Checker
    【LEETCODE】39、第561题 Array Partition I
    【LEETCODE】38、167题,Two Sum II
    【LEETCODE】37、122题,Best Time to Buy and Sell Stock II
    【LEETCODE】36、121题,Best Time to Buy and Sell Stock
    【LEETCODE】35、169题, Majority Element
  • 原文地址:https://www.cnblogs.com/or2-/p/3594678.html
Copyright © 2011-2022 走看看