删除表中重复记录,保留最小记录 OR 删除表中所有行重复记录
2012-02-10 16:47
776 查看
问题1:
有表如下:create Ta
(
id int identity(1,1) not null,
code varchar(10) null,
num float null
)
insert Ta(code,num)
select '001',100.00 union all
select '001',100.00 union all
select '001',500.00 union all
select '002',200.00 union all
select '002',200.00
/* 删除Ta表中字段 code,num 重复记录,保留ID值最小的记录*/
方法一:
select min(ID) RID ,code,num into #a from ta group by code,num having count(*)>1
delete from Ta where ID>(select RID from #a where #a.code=Ta.code and #a.num=Ta.num)
方法二:
delete from Ta where exists(select 1 from Ta T where Ta.code=T.code and Ta.num=T.num and Ta.ID>T.ID)
方法三:
with tb as(
select row_number() over(partition by code,num order by code,num,a ) newID,code,num from ta
)
delete from tb where newID>1
问题2:
有表TB 如下:create table Tb( code varchar(10) null,num float null)
insert Tb(code,num)
select '001',100.00 union all
select '001',100.00 union all
select '002',100.00 union all
select '002',200.00 union all
select '002',100.00
go
/* 删除Tb表中所有字段 存在重复记录 */
方法一: 连同重复的记录也一并删除了。
select code,num, count(*) as nid into #a from Ta group by code,num having count(*)>1
delete from Tb where exists(select 1 from #a where #a.code=code and #a.num=num)
方法二: 连同重复的记录也一并删除了。
with ch as(
select code,num from tb group by code,num having count(*)>1
)
delete from tb where not exists(select 1 from ch where ch.code=tb.code and ch.num=tb.num)
/* 删除Tb表中所有字段 重复记录 ,保留一条记录*/
方法一:
select distinct * into #a from tb
drop table tb
select * into tb from #a
drop table #a
方法二:
with ch as(
select row_number() over(partition by code,num order by code,num ) newID,* from tb
)
delete from ch where m>1
相关文章推荐
- oracle删除重复记录,只保留rowid最小的记录
- sql 删除重复记录,只保留ID号最小(或最大)的一条
- Mysql删除重复记录,保留id最小的一条
- sql 多个字段分组,删除重复记录,保留ID最小的一条
- 在oracle数据库表中删除所有重复的数据,仅保留一条记录
- 【方法3:Perl版本】删除Map中Value重复的记录,并且只保留Key最小的那条记录
- 初探oracle删除重复记录,只保留rowid最小的记录
- Mysql 删除重复记录,只保留最小的一条
- 删除oracle 表中重复数据sql语句、保留rowid最小的一条记录
- 【方法1】删除Map中Value重复的记录,并且只保留Key最小的那条记录
- Mysql删除重复记录,保留id最小的一条
- 【方法2】删除Map中Value重复的记录,并且只保留Key最小的那条记录
- Oracle查询重复数据并删除,只保留一条记录
- SQL 删除重复记录,并保留其中一条
- 删除数据库中重复的记录(保留一条)-oracle、mysql版
- 160802、1.06s删除10w条重复记录只保留一条(mysql)及linux删除乱码文件
- SQL语句实现删除重复记录并只保留一条
- mysql删除重复数据只保留id最大一条记录
- mysql删除重复记录,只保留一条。
- mysql删除重复记录,保存Id最小的一条