sql语句(50分)

  • 主题发起人 delphi188
  • 开始时间
D

delphi188

Unregistered / Unconfirmed
GUEST, unregistred user!
如何实现以下功能:
一个表中有n条记录的某一字段值是相同的,如何只留下相同记录中的第一条,
删除其余的几条?
 
笨方法:
先select到一个RS中
再delete all
最后把RS中的第一条insert回去
 
你的第一条的意思是什么?是任意一条?还是物理存储位置第一条,还是按照某个索引排序第一条...?
如果不关心物理存储位置的第一条:
create table temp_tab_name as select distinct(field1), field2, field3.... from
tab_name;
然后删除表tab_name
把表temp_tab_name改名为tab_name
OK
 
你知道这个相同字段值吗?如果其它字段的值不同呢是否要删除?
 
delete from table
where colum=value and ROWNUM>1
 
写一个存储过程吧,很简单,很高效!
 
to dxpjj:不知道这个相同字段的值,如果其它字段的值不同也要删除.
to :eric.youbin 我试试建临时表,刚学delphi,没用过这个
to:pluto_l 这个value指的是什么?ROWNUM是什么?

谢谢各位
 
方法原理:
1、Oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的,
  rowid确定了每条记录是在ORACLE中的哪一个数据文件、块、行上。

2、在重复的记录中,可能所有列的内容都相同,但rowid不会相同,所以只要确定出重复记录中
  那些具有最大rowid的就可以了,其余全部删除。

3、以下语句用到了3项技巧:rowid、子查询、别名。

实现方法:
SQL> create table a (
2 bm char(4), --编码
3 mc varchar2(20) --名称
4 )
5 /

表已建立.

SQL> insert into a values('1111','1111');
SQL> insert into a values('1112','1111');
SQL> insert into a values('1113','1111');
SQL> insert into a values('1114','1111');

SQL> insert into a select * from a;

插入4个记录.

SQL> commit;

完全提交.

SQL> select rowid,bm,mc from a;

ROWID BM MC
------------------ ---- -------
000000D5.0000.0002 1111 1111
000000D5.0001.0002 1112 1111
000000D5.0002.0002 1113 1111
000000D5.0003.0002 1114 1111
000000D5.0004.0002 1111 1111
000000D5.0005.0002 1112 1111
000000D5.0006.0002 1113 1111
000000D5.0007.0002 1114 1111

查询到8记录.


查出重复记录
SQL> select rowid,bm,mc from a where a.rowid!=(select max(rowid) from a b where a.bm=b.bm and a.mc=b.mc);

ROWID BM MC
------------------ ---- --------------------
000000D5.0000.0002 1111 1111
000000D5.0001.0002 1112 1111
000000D5.0002.0002 1113 1111
000000D5.0003.0002 1114 1111

删除重复记录
SQL> delete from a a where a.rowid!=(select max(rowid) from a b where a.bm=b.bm and a.mc=b.mc);

删除4个记录.

SQL> select rowid,bm,mc from a;

ROWID BM MC
------------------ ---- --------------------
000000D5.0004.0002 1111 1111
000000D5.0005.0002 1112 1111
000000D5.0006.0002 1113 1111
000000D5.0007.0002 1114 1111

希望能解决你的问题
 
select distinct 需要的全部字段 into newtabel from oldtabel where 条件
drap tabel oldtabel
name newtabel as oldtabel
 
delete from xxx where 主键字段 not in
(select top 1 主键字段 from xxx where 某一字段=某值 order by 主键)
 
多人接受答案了。
 
顶部