0

我正在做这个项目,我需要做的一件事是选择一些数据

桌子:

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

4

4 回答 4

2

以下查询将按 unit_id 对记录进行分组,并标识具有最新时间戳的记录,将这些结果与同一张表连接起来,并选择具有 unit_id 和时间戳值的记录。

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
于 2012-10-19T03:52:34.490 回答
2

通过使用 GROUP BY 子句,例如

SELECT 
    unit_id, max(TimeStamp)
FROM 
    table3
GROUP BY 
    unit_id
于 2012-10-19T03:55:11.300 回答
1

试试这个

SELECT unit_id , max(tstamp) 
FROM   t 
GROUP BY unit_id
于 2012-10-19T03:57:13.617 回答
0
SELECT max(timestamp),unit_id FROM table GROUP BY unit_id 
于 2012-10-19T04:00:07.220 回答