首页 热点 业界 科技快讯 数码 电子消费 通信 前沿动态 电商

oracle数据库去除重复数据常用的方法总结

2022-05-21 05:23:12 来源 : 软件开发网

目录

创建测试数据

针对指定列,查出去重后的结果集

distinct

row_number()

针对指定列,查出所有重复的行

count having

count over

删除所有重复的行

删除重复数据并保留一条

分析函数法

group by

总结

创建测试数据create table nayi224_180824(col_1 varchar2(10), col_2 varchar2(10), col_3 varchar2(10));insert into nayi224_180824select 1, 2, 3 from dual union allselect 1, 2, 3 from dual union allselect 5, 2, 3 from dual union allselect 10, 20, 30 from dual ;commit;select*from nayi224_180824;COL_1COL_2COL_3
123
123
523
102030
针对指定列,查出去重后的结果集distinctselect distinct t1.* from nayi224_180824 t1;COL_1COL_2COL_3
102030
123
523

方法局限性很大,因为它只能对全部查询的列做去重。如果我想对col_2,col3去重,那我的结果集中就只能有col_2,col_3列,而不能有col_1列。

select distinct t1.col_2, col_3 from nayi224_180824 t1COL_2COL_3
23
2030

不过它也是最简单易懂的写法。

row_number()select * from (select t1.*, row_number() over(partition by t1.col_2, t1.col_3 order by 1) rn from nayi224_180824 t1) t1 where t1.rn = 1;COL_1COL_2COL_3RN
1231
1020301

写法上要麻烦不少,但是有更大的灵活性。

针对指定列,查出所有重复的行count havingselect * from nayi224_180824 t where (t.col_2, t.col_3) in (select t1.col_2, t1.col_3 from nayi224_180824 t1 group by t1.col_2, t1.col_3 having count(1) > 1)COL_1COL_2COL_3
123
123
523

要查两次表,效率会比较低。不推荐。

count overselect * from (select t1.*, count(1) over(partition by t1.col_2, t1.col_3) rn from nayi224_180824 t1) t1 where t1.rn > 1;COL_1COL_2COL_3RN
1233
1233
5233

只需要查一次表,推荐。

删除所有重复的行delete from nayi224_180824 t where t.rowid in ( select rid from (select t1.rowid rid, count(1) over(partition by t1.col_2, t1.col_3) rn from nayi224_180824 t1) t1 where t1.rn > 1);

就是上面的语句稍作修改。

删除重复数据并保留一条分析函数法delete from nayi224_180824 t where t.rowid in (select rid from (select t1.rowid rid, row_number() over(partition by t1.col_2, t1.col_3 order by 1) rn from nayi224_180824 t1) t1 where t1.rn > 1);

拥有分析函数一贯的灵活性高的特点。可以为所欲为的分组,并通过改变orderby从句来达到像”保留最大id“这样的要求。

group bydelete from nayi224_180824 t where t.rowid not in (select max(rowid) from nayi224_180824 t1 group by t1.col_2, t1.col_3);

牺牲了一部分灵活性,换来了更高的效率。

总结

到此这篇关于oracle数据库去除重复数据常用的文章就介绍到这了,更多相关oracle去除重复数据内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

标签: 分析函数 测试数据 为所欲为

相关文章

最近更新
观焦点:超萌相机 2023-03-01 12:29:37
海南百货网 2023-03-01 12:13:44
焦点热讯:宜点充 2023-02-28 10:10:16
天天关注:小铺CEO 2023-02-28 10:07:13
【世界聚看点】KaFit 2023-02-28 09:31:37
葱天下 2023-02-28 09:17:03
渔界竞钓 2023-02-28 08:15:29
焦点快看:鲸奇视频 2023-02-28 06:30:37
环球热议:萝小逗 2023-02-27 23:25:49
简讯:小码公交 2023-02-27 23:16:12
彼岸花 2023-02-27 22:32:52
时时夺宝 2023-02-27 21:37:50
天天动态:袜之源 2023-02-27 21:29:50
天天资讯:AI空气 2023-02-27 20:19:46
世界时讯:绘读 2023-02-27 20:19:41
看点:一元得购 2023-02-27 19:26:28