Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176395
  • 博文数量: 30
  • 博客积分: 2170
  • 博客等级: 大尉
  • 技术积分: 375
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-13 11:13
文章分类

全部博文(30)

文章存档

2010年(1)

2009年(7)

2008年(22)

我的朋友

分类: 数据库开发技术

2008-11-06 21:11:21

有两个意义上的重复记录:
一是完全重复的记录,也即所有字段均重复的记录;
二是部分关键字段重复的记录,比如Name字段重复,而其他字段不一定重复;
 
1、对于第一种重复,比较容易解决,使用
 

select distinct * from tableName


就可以得到无重复记录的结果集。
如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除:

SQLServer:

select distinct * into #Tmp from tableName;
drop table tableName;
select * into tableName from #Tmp;
drop table #Tmp;

但是当tableName表中含有text、ntext 或 image 数据类型的字段时,上面的SQL语句将会报错:“不能以 DISTINCT 方式选择 text、ntext 或 image 数据类型”,这时可以使用第二种重复情况的SQL写法,用group分组的方式。

Oracle:

CREATE TABLE temp_table AS (select distinct * from tableName);
truncate table tableName;
insert into tableName(select * from temp_table);
drop table temp_table;

 

2、对于第二种重复,可以用下面的方法(未测试):

SQLServer:

select identity(int,1,1) as autoID, * into #Tmp from tableName;
drop table tableName;
select min(autoID) as autoID into #Tmp2 from #Tmp group by name,age;
select column1,column2,column3.... into tableName
from #Tmp where autoID in(select autoID from #tmp2);
drop table #Tmp;
drop table #tmp2;

Oracle:

可以借鉴上面SQLServer的思想;

阅读(602) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~