2015-10-05 45 views
0

想象你有如下表:SQL查詢中使用的日期檢索不同元素

table1: 

| sensor_id | event_type | value | date    | 
|---------------------------------------------------- 
| 2   | 2   | 2  | 2015:10:05 12:45 | 
| 2   | 2   | 54 | 2015:10:05 15:45 | 
| 2   | 3   | 7  | 2015:10:05 14:05 | 
| 3   | 2   | 5  | 2015:10:05 00:05 | 
| 3   | 2   | 5  | 2015:10:05 14:05 | 

而且你要檢索的最後一個值所有sensor_ids和event_types,通過sensor_id和EVENT_TYPE排序,所以,結果應該是:

| sensor_id | event_type | value | date    | 
|---------------------------------------------------- 
| 2   | 2   | 54 | 2015:10:05 15:45 | 
| 2   | 3   | 7  | 2015:10:05 14:05 | 
| 3   | 2   | 5  | 2015:10:05 14:05 | 

任何人都可以幫我查詢嗎?

+1

哪些DBMS您使用的? Postgres的?甲骨文? –

回答

2

這應該工作:

select sensor_id, event_type, value, date 
from table1 T1 
where date>= all (select max(date) from table1 T2 where 
T1.sensor_id = T2.sensor_id and T1.event_type = T2.event_type) 
order by sensor_id, event_type 
1

返回一行,如果不存在後用相同的ID行:

select sensor_id, event_type, value, date 
from tablename t1 
where not exists (select 1 from tablename t2 
        where t2.sensor_id = t1.sensor_id 
        and t2.event_type = t1.event_type 
        and t2.date > t1.date) 
order by sensor_id, event_type