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

后端 未结 7 1915
栀梦
栀梦 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:30

    I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.

    I have a table of sensor data (1 minute data from about 30 sensors)

    SensorReadings->(timestamp,value,idSensor)
    

    and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:

    Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
    

    The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:

    SELECT idSensor,Description,tvLastUpdate,tvLastValue 
    FROM Sensors
    

    I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.

提交回复
热议问题