首先我们创建测试表hoegh,插入3条记录。我们可以看到,就前两个字段而言,第二条记录和第三条记录是重复的。
点击(此处)折叠或打开
-
SQL>
-
SQL> create table hoegh(h1 number,h2 number,h3 number);
-
-
Table created
-
SQL> insert into hoegh values(1,1,1);
-
-
1 row inserted
-
SQL> insert into hoegh values(2,2,2);
-
-
1 row inserted
-
SQL> insert into hoegh values(2,2,8);
-
-
1 row inserted
-
SQL> commit;
-
-
Commit complete
-
-
SQL> select * from hoegh;
-
-
H1 H2 H3
-
---------- ---------- ----------
-
1 1 1
-
2 2 2
-
2 2 8
-
- SQL>
使用DISTINCT去重
如下:
点击(此处)折叠或打开
-
SQL>
-
SQL> select distinct h1,h2 from hoegh;
-
-
H1 H2
-
---------- ----------
-
1 1
- 2 2
-
- SQL>
使用group by去重
gruop by是Oracle中常用的分组函数,我们看一下如何使用group by来实现去重功能。
点击(此处)折叠或打开
-
SQL>
-
SQL> select h1,h2 from hoegh group by(h1,h2);
-
-
H1 H2
-
---------- ----------
-
1 1
-
2 2
-
- SQL>
点击(此处)折叠或打开
-
SQL>
-
SQL> delete from hoegh
-
2 where h3 not in (select max(h3) from hoegh group by h1,h2);
-
-
1 row deleted
-
-
SQL> commit;
-
-
Commit complete
-
-
SQL> select * from hoegh;
-
-
H1 H2 H3
-
---------- ---------- ----------
-
1 1 1
-
2 2 8
-
- SQL>
ROWID是数据的详细地址,通过rowid,oracle可以快速的定位某行具体的数据的位置。通过下面的语句,可以保留重复记录中的最新一条记录(即最后插入的那条记录)。
点击(此处)折叠或打开
-
SQL>
-
SQL> delete from hoegh
-
2 where rowid not in
-
3 (select max(rowid) from hoegh group by(h1,h2));
-
-
1 row deleted
-
-
SQL> commit;
-
-
Commit complete
-
-
SQL>
-
SQL> select * from hoegh;
-
-
H1 H2 H3
-
---------- ---------- ----------
-
1 1 1
-
2 2 8
-
- SQL>