当前位置: 代码迷 >> Sql Server >> 想保留有多条相同记录中的一行,删除其他多余的记录,sql语句如何写呀
  详细解决方案

想保留有多条相同记录中的一行,删除其他多余的记录,sql语句如何写呀

热度:8   发布时间:2016-04-25 01:18:15.0
想保留有多条相同记录中的一行,删除其他多余的记录,sql语句怎么写呀
数据库的一个表中,有多条相同的记录,想保留其中的一行记录,删除其他多余的记录,sql语句怎么写呀

------解决方案--------------------
如果完全相同的话,除了faq里面的方法,你还可用distinct把数据找出来然后查到一个临时表,然后删除源表的那些数据,再把临时表的数据插回去。
------解决方案--------------------
SQL code
select * from awhere ax in (select ax from a group by ax having count(ax) > 1)
------解决方案--------------------
SQL code
--保留一条(这个应该是大多数人所需要的 ^_^)Delete a Where ID Not In (Select Max(ID) From a Group By Title)
------解决方案--------------------

declare @t table(id int);

insert into @t
select 1 union all
select 2 union all
select 3 union all
select 2 union all
select 1 

;with c1 as
(
select row_number() over(partition by id order by id) rowid,
id
from @t
)
delete from c1 where rowid > 1

select * from @t order by id


id
-----------
1
2
3

(3 行受影响)



------解决方案--------------------
用distinct 最简单了。不过显示最新插入的也行,

select id,f1,f2 from t tt
where tt.id=
(select max(id)
from t
where tt.f1=t.f1 and tt.f2=t.f2)
  相关解决方案