2010-09-20 87 views
2

只返回最新值我有一個表結構如下:從時間戳表

timestamp, tagid, value 

我想查詢在那裏我可以爲標籤ID的列表只接收最新的時間戳值。例如:

SELECT * FROM floatTable WHERE tagid IN(1,2,3,4,5,6) 

將返回整組值。我只想爲每一個存儲最新的值。

回答

3
select f.timestamp, f.tagid, f.value 
from floatTable f 
inner join (
    select tagid, max(timestamp) as timestampMax 
    from floatTable 
    where tagid in (1,2,3,4,5,6) 
    group by tagid 
) fm on f.tagid = fm.tagid and f.timestamp = fm.timestampMax 
+0

大根據需要它執行。但是,有沒有辦法加快速度?由於表格非常大,因此返回單個tagid值需要4-5秒。 – user438199 2010-09-20 16:33:34

0

如何:

select vt.tagid, maxdate, t.value 
from 
    ( 
    select tagid, max(timestamp) as maxdate 
    from floatTable 
    group by tagid 
) vt 
inner join floatTable t on t.tagid = vt.tagid 
where t.timestamp = vt.maxdate 
and t.tagid in (1,2,3,4,5,6)