2014-07-11 48 views
5

篩選行。這是我的表結構:SQL:與最大值

File | Version  | Function 
1  | 1   | 1 
1  | 2   | 1 
1  | 3   | 1 
1  | 2   | 2 

2  | 1   | 4 
3  | 2   | 5 

我需要它返回這些行只

1  | 3   | 1 
2  | 1   | 4 
3  | 2   | 5 

含義我只希望有最新版本的功能爲每個文件。

我不希望下面的結果,即獨特功能的IDS是不是最新版本

1  | 3   | 1 
1  | 2   | 2 
... 

我已經看了How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?,但返回最近的獨特功能ID。

查詢需要sqlite3兼容。

回答

3

一個有效的方法,這樣做往往是使用not exists

select t.* 
from table t 
where not exists (select 1 
        from table t2 
        where t2.file = t.file and t2.Version > t.version 
       ); 

這種查詢可以在table(file, version)採取指數的優勢。

這會將查詢重新定義爲:「從表中找到相應文件沒有更大版本的表中的所有行。」

+0

prefectly的工作,謝謝。你可能看看我的下一個問題,因爲你解決了1/4的問題? http://stackoverflow.com/questions/24719716/sql-complex-sum-from-multiple-tables –

1

請注意,如果針對不同功能存在文件的最新版本,則這將爲每個文件返回多行。即如果您的示例上面有一個額外的行(1,3,2),則會爲文件1返回2行。

select 
    t1.file, 
    t1.version, 
    t1.function 
from 
    mytable t1 
join (
    select 
     t2.file, 
     max(t2.version) max_version   
    from mytable t2 
    group by t2.file 
) t3 join t1.file = t3.file and t1.version = t3.max_version 
2

在SQLite的3.7.11或更高版本,當您使用MAX,其他值都保證來自該行具有最大價值:

SELECT File, 
     MAX(Version) AS Version, 
     Function 
FROM MyTable 
GROUP BY File