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

后端 未结 7 1904
栀梦
栀梦 2020-12-04 06:49

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 o

7条回答
  •  暖寄归人
    2020-12-04 07:46

    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).

提交回复
热议问题