Oracle数据库中查询重复数据的方法

在 Oracle 数据库中,查询重复数据是一项常见任务,尤其是在处理大量数据时。重复的数据可能有两种情况:第一种是表中只有某些字段一样,第二种是两行记录完全一样。

今天十一张(www.11zhang.com)分享一种 Oracle 中快速查询重复数据的方法,希望对您有所帮助。

假设,现在有一张卡交易表(表名:card_table),这张表有卡号、交易日期、交易时间、设备编号4个字段,如下图。

select card_id    "卡号",
       trans_date "交易日期",
       trans_time "交易时间",
       eqp_id     "设备编号"
  from card_table;

Oracle中查询重复数据的方法

查询重复数据

若想将卡号、交易日期、交易时间、设备编号这4个字段完全相同的记录查询出来,我们可以据据 Oracle 自带的 rowid 属性来判断是否存在重复数据,语句如下:

select * from card_table a
 where a.rowid != (select max(b.rowid)
                     from card_table b
                    where a.card_id = b.card_id
                      and a.trans_date = b.trans_date
                      and a.trans_time = b.trans_time
                      and a.eqp_id = b.eqp_id);

删除重复数据

同理,若想将卡号、交易日期、交易时间、设备编号这4个字段完全相同的重复数据删除(只保留一条数据),语句如下:

delete from card_table a
 where a.rowid != (select max(b.rowid)
                     from card_table b
                    where a.card_id = b.card_id
                      and a.trans_date = b.trans_date
                      and a.trans_time = b.trans_time
                      and a.eqp_id = b.eqp_id);
commit;

查询非重复数据

我们也可以直接查询非重复数据(即不显示重复的数据),语句如下:

select a.*, rowid from card_table a
 where rowid in
       (select min(rowid) from card_table
         group by card_id,trans_date,trans_time,eqp_id)
 order by card_id asc;
✅来源:十一张博客
© 版权声明
THE END
如果觉得这篇文章对您有帮助,不妨考虑请我喝杯奶茶😄
点赞2赞赏 分享
评论 抢沙发
头像
评论人工审核通过显示,请勿重复提交!
提交
头像

昵称

取消
昵称表情代码

    暂无评论内容