本文为iihero原创,如若转载,请注明出处。谢谢。
为简化问题:
设表:t(id int, col2 varchar(32))
1. ASE:
选出重复的行:
select * from t group by id, col2 having count(*)>1
删掉重复的行,
alter table t add col3 int identity not null;
delete from t where col3 not in (select max(col3) from t group by id, col2);
alter table t drop col3; (前提select into/bulkcopy on数据库上的options)
2. ASA: (设表t123)
select * from t123
id,col2
1,'a'
1,'a'
2,'b'
3,'c'
delete from t123 where col3 not in (select max(col3) from t123 group by id, col2);
alter table t123 drop col3;
上述方法对ASE和ASA基本上是一样的。除了ASE中要求目标数据库select into为ON
3. ORACLE:
大概有两种方法:
方法1:基于rowid
delete from t a
where a.rowid !=
(
select max(b.rowid) from t b
where a.id = b.id and
a.col2 = b.col2
)
-
SQL> select * from t;
-
ID COL2
-
---------- --------------------------------
-
1 a
-
1 a
-
2 b
-
3 c
-
SQL> delete from t a where a.rowid != (select max(b.rowid) from t b where a.id=b.id and a.col2 = b.col2);
-
已删除 1 行。
-
SQL> select * from t;
-
ID COL2
-
---------- --------------------------------
-
1 a
-
2 b
-
3 c
SQL> select * from t;
ID COL2
---------- --------------------------------
1 a
1 a
2 b
3 c
SQL> delete from t a where a.rowid != (select max(b.rowid) from t b where a.id=b.id and a.col2 = b.col2);
已删除 1 行。
SQL> select * from t;
ID COL2
---------- --------------------------------
1 a
2 b
3 c
方法2:使用临时表
-
SQL> select * from t;
-
ID COL2
-
---------- --------------------------------
-
1 a
-
2 b
-
3 c
-
SQL> insert into t values(1, 'a');
-
已创建 1 行。
-
SQL> create table tt as select t.id, t.col2, max(t.rowid) dataid from t group by t.id, t.col2;
-
表已创建。
-
SQL> delete from t a where a.rowid != (select b.dataid from tt b where a.id=b.id and a.col2=b.col2);
-
已删除 1 行。
-
SQL> select * from t;
-
ID COL2
-
---------- --------------------------------
-
2 b
-
3 c
-
1 a
SQL> select * from t;
ID COL2
---------- --------------------------------
1 a
2 b
3 c
SQL> insert into t values(1, 'a');
已创建 1 行。
SQL> create table tt as select t.id, t.col2, max(t.rowid) dataid from t group by t.id, t.col2;
表已创建。
SQL> delete from t a where a.rowid != (select b.dataid from tt b where a.id=b.id and a.col2=b.col2);
已删除 1 行。
SQL> select * from t;
ID COL2
---------- --------------------------------
2 b
3 c
1 a
相信ASE/ASA也可以使用临时表的方案。(表特别大的时候,也许很有用)
至于MySQL/DB2当中的方法,应该是很类似的。不再赘述。
阅读(1190) | 评论(0) | 转发(0) |