您的位置:首页 > 数据库

[sql]删除重复的字段,保留一个。

2011-09-20 17:54 190 查看
其实有两个情况,1是完全重复。(设计时没有设定identity)

完全重复:

select distinct 字段,字段[,..] from table --找到不重复的记录……

--这类重复需求通常是需要添加一个identity字段

部分重复,指定字段重复,其他字段重复忽略不计(保留) (已经有identity的id了)

select max(id) as id ,重复字段,重复字段 from table group by 重复字段,重复字段 having count(*)>1

--找到重复的字段

删除和保留操作。

仅仅说第二种情况

select max(id) as id ,重复字段,重复字段 into #temp from table group by 重复字段,重复字段 having count(*)>1

delete from table where 重复字段 in (select 重复字段 from #temp ) [ and 重复字段 in (select 重复字段 from #temp ) ...]

and id not in (select id from #temp)

多个重复字段应多个[]语句。

当然也会有第三种情况,就是没有identity,但是也要部分重复

先给这个表加上identity

select identity(int , 1 , 1) as id ,字段,字段 into table2 from table1

之后就变成第二种情况了。

附上实验数据

create table testtable (
id int identity(1,1),
[name] varchar(100) default('')
)
alter table testtable
add addr varchar (1000)
go

insert into testtable values('x','a')
insert into testtable values('hello','addddd')insert into testtable values('helloxxxxxxxxx','addddd')

有参考到这个文章

http://www.cnblogs.com/zywuhao/archive/2011/02/11/1951177.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: