承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601

SQL中遇到多条相同内容只取一条的最简单实现方法

管理员 2023-06-23 06:23:41 互联网圈 15 ℃ 0 评论 2522字 收藏

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

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

以下:表timeand

/upload/allimg/2023/04/25/usktlktuj43.jpg

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

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

/upload/allimg/2023/04/25/dxzixnvkmbd.jpg

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

/upload/allimg/2023/04/25/3sqaq1uhijf.jpg

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

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

/upload/allimg/2023/04/25/gkon4qjfuen.jpg

此中方案排除方案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中遇到多条相同内容只取一条的最简单实现方法

https://www.wanzijz.com/view/58477.html

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信