我想按时间戳和UnitID选择Info。下面是两张桌子:
表格信息:
ID | UnitID | Time | Info
-----------------------------------------------
1 | 101 | 2011-07-20 08:22:02 | info 101
2 | 102 | 2011-07-21 08:22:02 | info 102
3 | 103 | 2011-07-22 08:22:02 | info 103
4 | 104 | 2011-07-23 08:22:02 | info 104
5 | 104 | 2011-07-25 08:22:02 | info 104
6 | 102 | 2011-07-26 08:22:02 | info 102
我想要的结果是每个UnitID一个,以及此UnitID的最新时间(时间戳):
ID | UnitID | Time | Info
------------------------------------------------
1 | 101 | 2011-07-20 08:22:02 | info 101
3 | 103 | 2011-07-22 08:22:02 | info 103
5 | 104 | 2011-07-25 08:22:02 | info 104
6 | 102 | 2011-07-26 08:22:02 | info 102
如何进行此查询?
答案 0 :(得分:1)
SELECT t1.ID, t1.UnitID, t2.MaxTime, t1.Info
FROM Info t1
INNER JOIN (SELECT UnitID, MAX(Time) As MaxTime
FROM Info
GROUP BY UnitID) AS t2
ON (t1.UnitD = t2.UnitID AND t1.Time = t2.MaxTime)
答案 1 :(得分:0)
试试这个 -
SELECT t1.* FROM table1 t1
JOIN (
SELECT UnitID, MAX(Time) maxtime FROM table1 GROUP BY UnitID
) t2
ON t1.UnitID = t2.UnitID AND t1.Time = t2.maxtime;
使用实际的表名更改'table1'。
答案 2 :(得分:0)
也许这个?
SELECT * FROM Info GROUP BY UnitID HAVING Time = MAX(Time);