2016-10-06 91 views
-1

我有一個表如何從sql表中獲取最大值與group by?

Id | Version | DateFrom | DateTo  | 
_______________________________________ 
1 | 1  | 2015-09-15 | 2015-09-18 | 
1 | 2  | 2015-09-15 | 2015-09-18 | 
1 | 3  | 2015-09-15 | 2015-09-20 | --different date 
1 | 4  | 2015-09-15 | 2015-09-18 | 
2 | 1  | 2015-09-15 | 2015-09-18 | 
2 | 2  | 2015-09-15 | 2015-09-18 | 

而我試圖讓與最新版本的獨立於其他列則返回記錄的視圖。 因此,例如我想到:

Id | Version | DateFrom | DateTo  | 
_______________________________________ 
1 | 4  | 2015-09-15 | 2015-09-18 | 
2 | 2  | 2015-09-15 | 2015-09-18 | 

這是我已經做了:

Select 
    Id, 
    MAX([Version]) AS Version, 
    DateFrom, 
    DateTo 
FROM 
    dbo.Table_1 
Group By 
    Id, 
    DateFrom, 
    DateTo 

但結果是:

Id | Version | DateFrom | DateTo  | 
_______________________________________ 
1 | 4  | 2015-09-15 | 2015-09-18 | 
1 | 3  | 2015-09-15 | 2015-09-20 | 
2 | 2  | 2015-09-15 | 2015-09-18 | 
+0

爲什麼不'GROUP BY Id' ? –

+0

@RuslanOsmanov,GROUP BY無效。不會在較新的MySQL版本上執行。 – jarlh

+0

@jarlh,即使它會(有一個選項允許它),通過'ID'分組將不起作用。 – sagi

回答

1

也可以用左做加盟:

SELECT t.* 
FROM YourTable t 
LEFT JOIN YourTable s 
ON(t.id = s.id AND t.version < s.version) 
WHERE s.version is null 
0

有一個子查詢,返回每個ID的最大版。與結果加入:

select t1.* 
from tablename t1 
join (select id, max(version) as maxversion 
     from tablename 
     group by id) t2 
    on t1.id = t2.id and t1.version = t2.maxversion 
0

您可以運行查詢類型:

Select ID, version, dateFrom, dateTo 
from table_1 a 
where not exists (
select 1 
from table_1 b 
where a.id = b.id and a.version < b.version)