日期:2014-05-18  浏览次数:20342 次

一个删除重复数据的语句
表   t
只有字段   a

a

1
1
2
3
4
5
6

要求吧重复的数据删除了,就留一条

结果
a
1
2
3
4
5
6

------解决方案--------------------
delete from 表 where id in
(
Select id from 表 as aa where exists
(select * from 表 where aa.a=表.a and aa.id <表.id )
)

------解决方案--------------------
如果仅仅为了查询
select distinct a from t

如果要物理删除
select distinct a into #temp from t
drop table t
select * into from #temp
------解决方案--------------------
create table test(a int)
insert test select 1
union all select 1
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6

alter table test add id int identity(1,1)
go

delete from test where id in
(
select id from test as T
where id > (select min(id) from test where a=T.a)
)

select a from test

alter table test drop column id

drop table test

a
-----------
1
2
3
4
5
6
------解决方案--------------------
呵呵,這道題和我剛面試的題目差不多!我當時是如下做的
Select distinct a Into TempA From T

Select * Into T From TempA
Select * From T
Drop Table TempA
我當時這樣做了,人家說這種方法是可以達到目的,不過不是他們所要求的答案!
------解决方案--------------------
select distinct a into #tab from tablename
delete table tablename
insert into tablename select * from #tab

------解决方案--------------------

delete from test where id
not in (select max(id) as id from test group by a)
------解决方案--------------------

select distinct a into #tab from t

delete from dbo.t //这里不能用drop table tablename 这样的话就删除掉了物理表了

insert into t select * from #tab
先筛选出符合条件的数据插入到临时表中
再删除整个表中的数据
最后在把临时表中的数据插入到表中


这样的话我自我感觉执行的效率不高,显得挺笨的一种方法

------解决方案--------------------
你这样一搞,原表t中的一些什么约束呀,关键主键呀,这些不都没有了?
所以说这些结果都不理想吧?
貌似下面的比较好点吧;
delete from 表 where id in
(
Select id from 表 as aa where exists
(select * from 表 where aa.a=表.a and aa.id <表.id )
)