2017-08-03 25 views
0

例如從MySQL表中選擇最新的(高達某個日期)每個變量的記錄的表結構的

VarName Date Machine 
------------------------- 
A date1  machine1 
B date2  machine1 
A date3  machine2 
C date4  machine2 
A date5  machine1 
C date6  machine1 
A date7  machine1 

我試圖從我的數據庫來過濾應該是這樣的:

VarName Date Machine 
    ------------------------- 
    A date1  machine1 
    B date2  machine1 
    C date6  machine1 

每個變量只能被選中一次,每個變量必須是最新記錄到某個日期。我的發言條件是(WHERE date <= 'some date' AND machine='SomeMachineName')。加入聲明可能是解決方案,但我沒有嘗試過任何事情。

謝謝您的幫助

回答

1

一種方法是使用相關子查詢的where子句中:

select t.* 
from t 
where t.date = (select max(t2.date) 
       from t t2 
       where t2.varname = t.varname and 
         t2.date <= @date 
       ); 

出於性能考慮,你想對t(varname, date)的索引。

+0

非常感謝。這是我一直在尋找的 –

0

有派生表(子查詢),它返回每個VarName的最後日期。加入結果:

select t1.* 
from tablename t1 
join (select VarName, max(Date) Date 
     from tablename 
     group by VarName) t2 
    on t1.Varname = t2.VarName and t1.Date = t2.Date 
+0

您錯過了WHERE條款,請參閱Gordon的答案。因此,在發佈之前花時間確保您的答案是正確的重要性:-) –

+0

@TimBiegeleisen,是的,也是OP應該發佈查詢嘗試的原因之一... – jarlh

+0

@jarlh或者可能是我們爲什麼選擇應該拒絕發佈答案,直到提供足夠的信息! – Strawberry

相關問題