sql 删除重复记录没有大小关系时,处理重复值

php中文网
发布: 2016-06-07 17:47:31
原创
973人浏览过

sql 删除重复记录没有大小关系时,处理重复值

sql 删除重复记录没有大小关系时,处理重复值


--> --> (roy)生成

if not object_id('tempdb..#t') is null     drop table #t go create table #t([num] int,[name] nvarchar(1)) insert #t select 1,n'a' union all select 1,n'a' union all select 1,n'a' union all select 2,n'b' union all select 2,n'b' go

方法1:

if object_id('tempdb..#') is not null
    drop table #
select distinct * into # from #t--排除重复记录结果集生成临时表#

truncate table #t--清空表

insert #t select * from #    --把临时表#插入到表#t中

--查看结果
select * from #t

/*
num         name
----------- ----
1           a
2           b

(2 行受影响)
*/

--重新执行测试数据后用方法2
方法2:

alter table #t add id int identity--新增标识列
go
delete a from  #t a where  exists(select 1 from #t where num=a.num and name=a.name and id>a.id)--只保留一条记录
go
alter table #t drop column id--删除标识列

--查看结果
select * from #t

/*
num         name
----------- ----
1           a
2           b

(2 行受影响)

AletheaAI
AletheaAI

世界上第一个从自然语言描述中生成交互式 AI 角色的多模态 AI 系统。

AletheaAI 83
查看详情 AletheaAI

*/

--重新执行测试数据后用方法3
方法3:

declare roy_cursor cursor local for
select count(1)-1,num,name from #t group by num,name having count(1)>1
declare @con int,@num int,@name nvarchar(1)
open roy_cursor
fetch next from roy_cursor into @con,@num,@name
while @@fetch_status=0
begin
    set rowcount @con;
    delete #t where and
    set rowcount 0;
    fetch next from roy_cursor into @con,@num,@name
end
close roy_cursor
deallocate roy_cursor

--查看结果
select * from #t
/*
num         name
----------- ----
1           a
2           b

(2 行受影响)
*/
//利用

declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0

//使用函数

select distinct * into #tmp from tablename
drop table tablename
select * into tablename from #tmp
drop table #tmp

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号