SQL語句重複數據取一條

SQL中常常遇到以下狀況,在一張表中有兩條記錄基本徹底同樣,某個或某幾個字段有些許差異,
這時候可能須要咱們踢出這些有差異的數據,即兩條或多條記錄中只保留一項。
以下:表timeand

針對time字段相同時有不一樣total和name的情形,每當遇到相同的則只取其中一條數據,最簡單的實現方法有兩種
一、sql

select time,max(total) as total,name from timeand group by time;

//取記錄中total最大的值

spa

select time,min(total) as total,name from timeand group by time;

//取記錄中total最小的值

上述兩種方案都有個缺點,就是沒法區分name字段的內容,因此通常用於只有兩條字段或其餘字段內容徹底一致的狀況

二、code

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



此中方案排除了方案1中name字段不許確的問題,取的是total最大的值

上面的例子中是隻有一個字段不相同,假若有兩個字段出現相同呢?要求查處第三個字段的最大值該如何作呢?
其實很簡單,在原先的基礎上稍微作下修改便可:
原先的SQL語句:
class

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

相關文章
相關標籤/搜索