利用row_number over 函数删除重复记录

开窗函数          
     Oracle从8.1.6开始提供分析函数,分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个组返回多行,而聚合函数对于每个组只返回一行

 


SQL> create table a1(id int,flag1 char(10),flag2 char(10));

Table created.

SQL> select * from a1;

 ID FLAG1      FLAG2
---------- ---------- ----------
  1 a       a1
  1 a       a2
  1 b       b1
  1 b       b2

SQL>  delete from (select unique a.* from a1 a);
 delete from (select unique a.* from a1 a)
             *
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL> delete from (select * from (select unique a.* from a1 a));
delete from (select * from (select unique a.* from a1 a))
            *
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-preserved table


SQL> delete from (select * from a1 group by id,name);
delete from (select * from a1 group by id,name)
            *
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view

SQL>  select a.*,row_number() over(partition by id,flag1 order by id,flag1) as num from a1 a;

 ID FLAG1      FLAG2  NUM
---------- ---------- ---------- ----------
  1 a       a1    1
  1 a       a2    2
  1 b       b1    1
  1 b       b2    2

SQL> delete from (select a.*,row_number() over(partition by id,flag1 order by id,flag1) as num from a1 a) where num>1;
delete from (select a.*,row_number() over(partition by id,flag1 order by id,flag1) as num from a1 a) where num>1
            *
ERROR at line 1:
ORA-01732: data manipulation operation not legal on this view


SQL> (select a.*,
                            row_number() over(partition by id, flag1 order by id, flag1) as num
                       from a1 a)  2    3  ;

 ID FLAG1      FLAG2  NUM
---------- ---------- ---------- ----------
  1 a       a1    1
  1 a       a2    2
  1 b       b1    1
  1 b       b2    2

SQL> delete from a1 where rowid in  (select rowid
               from (select a.*,
                            row_number() over(partition by id, flag1 order by id, flag1) as num
                       from a1 a)a
              where num >= 2)  2    3    4    5 
  6  ;

2 rows deleted.

SQL> commit;

Commit complete.

SQL> select * from a1;

 ID FLAG1      FLAG2
---------- ---------- ----------
  1 a       a1
  1 b       b1

 

 

 

你可能感兴趣的:(row_number)