有两个意义上的重复记录:
一是完全重复的记录,也即所有字段均重复的记录;
二是部分关键字段重复的记录,比如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) |