lundi 6 avril 2015

How to select the value from recent record?

I have table



create table events (
sensor_id integer not null,
event_type integer not null,
value integer not null,
time timestamp unique not null);

insert into events
values
(2,2,5,"2014-02-13 12:42:00"),
(2,4,-42,"2014-02-13 13:19:57"),
(2,2,2,"2014-02-13 14:48:30"),
(3,2,7,"2014-02-13 12:54:39"),
(2,3,54,"2014-02-13 13:32:36");


I want for each sensor_id and event_type only the most recent value in terms of time


expected result



sensor_id, event_type value
2 2 2
2 3 54
2 4 -42
3 2 7


I have tried query



SELECT sensor_id,event_type,value, time
from events
group by sensor_id,event_type
having time = max(time)


why it doesn't success (result table do not contain sensor_id = 2 and event_type = 2)


How could I solve this using both mysql and sqllite, is there difference in term of this ?


Aucun commentaire:

Enregistrer un commentaire