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類型

相關文章
相關標籤/搜索