我正在研究这个项目,我需要做的一件事就是选择一些数据
表:
id | unit_id | data1 | data2 | data 3 | data4 | TimeStamp
1 | 1 | 1 | 1 | 1 | 2012-10-18 18:17:42
2 | 1 | 2 | 2 | 2 | 2012-10-18 18:18:42
3 | 1 | 3 | 5 | 3 | 2012-10-20 18:19:42
4 | 1 | 4 | 7 | 4 | 2012-10-21 18:20:42
5 | 1 | 5 | 8 | 8 | 2012-10-22 18:21:42
6 | 2 | 1 | 1 | 1 | 2012-10-18 18:17:42
7 | 2 | 2 | 2 | 4 | 2012-10-19 18:18:42
8 | 2 | 3 | 2 | 5 | 2012-10-20 18:19:42
9 | 2 | 4 | 3 | 6 | 2012-10-21 18:20:42
我需要的是获得Single LATEST value for EACH unit_id
答案 0 :(得分:2)
以下查询将按unit_id对记录进行分组,并标识具有最新时间戳的记录,将这些结果与同一表连接,并选择具有unit_id和timestamp值的记录。
SELECT
a.*
FROM
MyTable a
JOIN (SELECT
unit_id,
MAX(TimeStamp) 'TimeStamp'
FROM
MyTable
GROUP BY unit_id
) as b
ON a.unit_id = b.unit_id AND a.Timestamp = b.TimeStamp
答案 1 :(得分:2)
使用GROUP BY子句,如
SELECT
unit_id, max(TimeStamp)
FROM
table3
GROUP BY
unit_id
答案 2 :(得分:1)
试试这个
SELECT unit_id , max(tstamp)
FROM t
GROUP BY unit_id
答案 3 :(得分:0)
SELECT max(timestamp),unit_id FROM table GROUP BY unit_id