日期:2014-05-17  浏览次数:20503 次

删除重复数据
本帖最后由 xiongxing318 于 2012-11-14 15:48:09 编辑 有表AddressBookLinkMan 字段LinkManId  AddressBookId
没主键,我要查询出2个字段完全重复的数据,并且删除。只留下一条!!
             LinkManId         AddressBookId
              a1                   w
            a1                   w
            b1                   c
如上第一条跟第二条完全重复,我要删掉一条留一条sql怎么写??不使用临时表,以及加临时字段。就一条sql语句能解决吗????
------最佳解决方案--------------------
delete a from (select *,
 row_number() over(partition by LinkManId,AddressBookId order by LinkManId) no from AddressBookLinkMan ) a
 where a.no>1
------其他解决方案--------------------

--临时表
select distinct * into #Tmp from AddressBookLinkMan
drop table AddressBookLinkMan
select * into AddressBookLinkMan from #Tmp
drop table #Tmp


如果你添加的唯一列,就可以按照这种方式删除了:
http://bbs.csdn.net/topics/240034273
------其他解决方案--------------------
在线等啊。如果没法子就只能用临时表或者临时字段了
------其他解决方案--------------------
表竟然没有主键,我也没有其他好办法了。
------其他解决方案--------------------
引用:
SQL code?123456--临时表select distinct * into #Tmp from AddressBookLinkMandrop table AddressBookLinkManselect * into AddressBookLinkMan from #Tmpdrop table #Tmp

如果你添加的唯一列,就可以按照这种方式删除了:
h……
    蛋疼的就是没主键啊。。 真的没其他法子了么。。
------其他解决方案--------------------
SQL SERVER 2012支持 with表达式的删除!


declare @T TABLE
([LinkManId] varchar(2),[AddressBookId] varchar(1))
insert @T
select 'a1','w' union all
select 'a1','w' union all
select 'b1','c'

;with maco as 
(
select 
row_number() over (partition by [LinkManId],[AddressBookId] order by (select 1) ) as id,

from @T
)
delete from maco where id<>1 

select * from @T
/*
LinkManId AddressBookId
--------- -------------
a1        w
b1        c

(2 行受影响)
*/

------其他解决方案--------------------
create table #A(id int)
insert into #A
select 1
union all
select 1
union all
select 2
union all
select 2
------测试
with TB as (
select *,ROW_NUMBER()over(partition by id order by id) as rowid