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

后端 未结 7 1901
栀梦
栀梦 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:29

    There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.

    SELECT sensorID,timestamp,sensorField1,sensorField2 
    FROM (
        SELECT sensorID,timestamp,sensorField1,sensorField2
            , ROW_NUMBER() OVER(
                PARTITION BY sensorID
                ORDER BY timestamp
            ) AS rn
        FROM sensorTable s1
    WHERE rn = 1
    ORDER BY sensorID, timestamp;
    

    I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.

提交回复
热议问题