Oracle exists用法,查找相同或相似数据

SQL中经常遇到如下情况,在一张表中有两条记录基本完全一样,某个或某几个字段有些许差别,

这时候可能需要我们踢出这些有差别的数据,即两条或多条记录中只保留一项。

如下:表timeand

https://i-blog.csdnimg.cn/blog_migrate/f4085a4cd49068f66775262128431789.jpeg

针对time字段相同时有不同total和name的情形,每当遇到相同的则只取其中一条数据,最简单的实现方法有两种

1、select time,max(total) as total,name from timeand group by time;//取记录中total最大的值

https://i-blog.csdnimg.cn/blog_migrate/8dc97d3127825d65435486cae205d29d.jpeg

或 select time,min(total) as total,name from timeand group by time;//取记录中total最小的值

https://i-blog.csdnimg.cn/blog_migrate/da53e8b2b7cb14f73bb1b3ae64a2b0f3.jpeg

上述两种方案都有个缺点,就是无法区分name字段的内容,所以一般用于只有两条字段或其他字段内容完全一致的情况

2、select * from timeand as a where not exists(select 1 from timeand where a.time = time and a.total<total);

https://i-blog.csdnimg.cn/blog_migrate/e4f6d0db2c171758c8d09e37acb2fbd1.jpeg

此中方案排除了方案1中name字段不准确的问题,取的是total最大的值

上面的例子中是只有一个字段不相同,假如有两个字段出现相同呢?要求查处第三个字段的最大值该如何做呢?

其实很简单,在原先的基础上稍微做下修改即可:

原先的SQL语句:

select * from timeand as a where not exists(select 1 from timeand where a.time = time and a.total<total);

可修改为:

select * from timeand as a where not exists(select 1 from timeand where a.time = time and (a.total<total or (a.total=total and a.outtotal<outtotal)));

其中outtotal是另外一个字段,为Int类型

以上就是SQL中遇到多条相同内容只取一条的最简单实现方法的全部内容

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值