2012-10-19 73 views
0

我的項目,那我需要做的事情之一工作的一個最新值,是選擇一些數據創建SQL查詢來獲取每個UNIT_ID

表:

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

回答

2

下面的查詢將GROUP BY 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 
2

通過使用GROUP BY子句,像

SELECT 
    unit_id, max(TimeStamp) 
FROM 
    table3 
GROUP BY 
    unit_id 
1

試試這個

SELECT unit_id , max(tstamp) 
FROM t 
GROUP BY unit_id 
0
SELECT max(timestamp),unit_id FROM table GROUP BY unit_id