源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-06-09 13:12 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:SQL中遇到多条相同内容只取一条的最简单实现方法
SQL中经常遇到如下情况,在一张表中有两条记录基本完全一样,某个或某几个字段有些许差别, 这时候可能需要我们踢出这些有差别的数据,即两条或多条记录中只保留一项。 [b]如下:表timeand[/b] [img]http://files.jb51.net/file_images/article/201606/201606120940063.jpg[/img] [b]针对time字段相同时有不同total和name的情形,每当遇到相同的则只取其中一条数据,最简单的实现方法有两种[/b] 1、select time,max(total) as total,name from timeand group by time;//取记录中total最大的值 [img]http://files.jb51.net/file_images/article/201606/201606120940064.jpg[/img] 或 select time,min(total) as total,name from timeand group by time;//取记录中total最小的值 [img]http://files.jb51.net/file_images/article/201606/201606120940065.jpg[/img] 上述两种方案都有个缺点,就是无法区分name字段的内容,所以一般用于只有两条字段或其他字段内容完全一致的情况 2、select * from timeand as a where not exists(select 1 from timeand where a.time = time and a.total<total); [img]http://files.jb51.net/file_images/article/201606/201606120940066.jpg[/img] 此中方案排除了方案1中name字段不准确的问题,取的是total最大的值 [b]上面的例子中是只有一个字段不相同,假如有两个字段出现相同呢?要求查处第三个字段的最大值该如何做呢?[/b] 其实很简单,在原先的基础上稍微做下修改即可: [b]原先的SQL语句:[/b] select * from timeand as a where not exists(select 1 from timeand where a.time = time and a.total<total); [b]可修改为:[/b] 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)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部