在一表中怎样用sql语句删除重复的数据,只保留其中的一条数据?

时间:2021-11-25 14:49:05
在一表中有很多重复的数据比如:绿单号:123456有三条相同的数据,2365489有两条相同的数据,5698745有四条相同的数据,等等很多的这种情况,就是说有很多不同的绿单号有两到四条相同的数据。
我用sql语句该怎样删除多余的数据而保留其中的一条数据?
sql语句怎样写?

12 个解决方案

#1


delete from yourTABLE where yourFIELD not in (select min(yourFIELD) from yourTABLE group by FIELD1,FIELD2)

#2


看不明白?

#3


up

#4


通过中间表转吧。
用 Insert into TABLE Select Distinct FIELD from TABLE
删除当前表数据
在把临时表的数据倒回来

#5


/* 将过滤的数据放入临时表*/
select distinct * 
into #temp
from t1
order by s_id  

/*删除原表的数据*/
delete from t1

/*将甩选的数据插入原表
insert 
t1
select *
from #temp

/*删除临时表
drop table #temp
select * from t1

#6


2楼的就不错啊,你要加别的条件再加and就行啦

楼上两位的效率只怕很有点低吧

#7


楼主:没有明確説明是什麼数据庫、因此大家給出不同的答案。
   SQL Server .or. Access?

#8


delete from 表名
where 绿单号 in(select 绿单号 from 表名 group by 绿单号 having count(*) > 1)
and (您要删除的绿单号的条件)

#9


老大 

有相同的数据应考虑数据库的设计是否合理

不如怎么可能出现这样的情况呢

#10


create table t1(id int identity(0,1),a varchar(10),b varchar(10))
insert t1(a,b)
select 'aa','bb'
union all select 'a1','bgb'
union all select 'aa','bb'
union all select 'a2','bb'
union all select 'aa3','beeb'
union all select 'aa','bb'
union all select 'a2','bb'



delete t1 
where id not in 
(select min(id) as id from t1 group by a,b)----------------a,b重复.-----------

#11


谢谢各位!!

#12


怎么给不了分?

#1


delete from yourTABLE where yourFIELD not in (select min(yourFIELD) from yourTABLE group by FIELD1,FIELD2)

#2


看不明白?

#3


up

#4


通过中间表转吧。
用 Insert into TABLE Select Distinct FIELD from TABLE
删除当前表数据
在把临时表的数据倒回来

#5


/* 将过滤的数据放入临时表*/
select distinct * 
into #temp
from t1
order by s_id  

/*删除原表的数据*/
delete from t1

/*将甩选的数据插入原表
insert 
t1
select *
from #temp

/*删除临时表
drop table #temp
select * from t1

#6


2楼的就不错啊,你要加别的条件再加and就行啦

楼上两位的效率只怕很有点低吧

#7


楼主:没有明確説明是什麼数据庫、因此大家給出不同的答案。
   SQL Server .or. Access?

#8


delete from 表名
where 绿单号 in(select 绿单号 from 表名 group by 绿单号 having count(*) > 1)
and (您要删除的绿单号的条件)

#9


老大 

有相同的数据应考虑数据库的设计是否合理

不如怎么可能出现这样的情况呢

#10


create table t1(id int identity(0,1),a varchar(10),b varchar(10))
insert t1(a,b)
select 'aa','bb'
union all select 'a1','bgb'
union all select 'aa','bb'
union all select 'a2','bb'
union all select 'aa3','beeb'
union all select 'aa','bb'
union all select 'a2','bb'



delete t1 
where id not in 
(select min(id) as id from t1 group by a,b)----------------a,b重复.-----------

#11


谢谢各位!!

#12


怎么给不了分?