欢迎您来到中国万网客户服务中心!
客服导航
如果您在使用我们的产品中遇到问题,建议您首先在“常见问题”中查询解决方法;
如果没有找到该问题的解决方法,您可以在“问题搜索”中进行搜索;
如果搜索后没有找到满意答案,您可以“在线提问”,我们会在1个工作日内给您答复。
您现在的位置: 中国万网客服中心 >> 常见问题 >> 主机常见问题 >> 数据库 >> 文章正文

如何删除表中的重复记录?

作者:客服中心    文章来源:本站原创    点击数:    更新时间:2006-10-23

我们先从以下例子来分析
--测试数据
/*-----------------------------
select * from tt
-----------------------------*/
id          pid        
----------- -----------
1           1
1           1
2           2
3           3
3           3
3           3

(所影响的行数为 6 行)

首先,如何查询table中有重复记录
select *,count(1) as rownum
from tt
group by id, pid
having count(1) > 1
id          pid         rownum     
----------- ----------- -----------
1           1           2
3           3           3

(所影响的行数为 2 行)

方法一:使用distinct和临时表
if object_id('tempdb..#tmp') is not null
drop table #tmp
select distinct * into #tmp from tt
truncate table tt
insert into tt select * from #tmp
方法二:添加标识列
alter table tt add NewID int identity(1,1)
go 
delete from tt  where exists(select 1 from tt a where  a.newid>tt.newid and tt.id=a.id and tt.pid=a.pid)
go
alter table tt drop column NewID
go

--测试结果
/*-----------------------------
select * from tt
-----------------------------*/
id          pid        
----------- -----------
1           1
2           2
3           3

(所影响的行数为 3 行)


返回上一页
中国万网旗下网站:中国万网 买麦网
Copyright © 2007 中国万网 版权所有
推荐使用1024×768分辨率浏览,并关闭窗口弹出阻止程序