Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select rows with most recent timestamp for each key value?

I have a table of sensor data. Each row has a sensor id, a timestamp, and other fields. I want to select a single row with latest timestamp for each sensor, including some of the other fields.

I thought that the solution would be to group by sensor id and then order by max(timestamp) like so:

SELECT sensorID,timestamp,sensorField1,sensorField2  FROM sensorTable  GROUP BY sensorID  ORDER BY max(timestamp); 

This gives me an error saying that "sensorField1 must appear in the group by clause or be used in an aggregate."

What is the correct way to approach this problem?

like image 713
franklynd Avatar asked Jun 26 '13 17:06

franklynd


People also ask

How do I select a record with latest timestamp in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How do I get the most recent entry in SQL?

Here is the syntax that we can use to get the latest date records in SQL Server. Select column_name, .. From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table.

How do I do a timestamp in SQL?

The basic syntax of “timestamp” data type in SQL is as follows : Timestamp 'date_expression time_expression'; A valid timestamp data expression consists of a date and a time, followed by an optional BC or AD.


1 Answers

For the sake of completeness, here's another possible solution:

SELECT sensorID,timestamp,sensorField1,sensorField2  FROM sensorTable s1 WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID) ORDER BY sensorID, timestamp; 

Pretty self-explaining I think, but here's more info if you wish, as well as other examples. It's from the MySQL manual, but above query works with every RDBMS (implementing the sql'92 standard).

like image 85
fancyPants Avatar answered Sep 27 '22 22:09

fancyPants