使用日期

时间:2015-10-05 13:50:06

标签: 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 |

有人可以帮我查询吗?

2 个答案:

答案 0 :(得分: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 :(得分: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