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

SQL中常常遇到以下状况,在一张表中有两条记录基本彻底同样,某个或某几个字段有些许差异,.net

这时候可能须要咱们踢出这些有差异的数据,即两条或多条记录中只保留一项。基础

以下:表timeandfile

http://files.jb51.net/file_images/article/201606/201606120940063.jpg

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

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

http://files.jb51.net/file_images/article/201606/201606120940064.jpg

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

http://files.jb51.net/file_images/article/201606/201606120940065.jpg

上述两种方案都有个缺点,就是没法区分name字段的内容,因此通常用于只有两条字段或其余字段内容彻底一致的状况数据

二、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

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

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

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

原先的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类型

相关文章
相关标签/搜索