Question

I have a table that keeps up with device state changes in a room, and need to write a query that lists the amount of time since the last state change. The table consists of the fields, new_state, prev_state, room, timestamp. My latest try was

SELECT a.room, a.prev_state, a.new_state, 
timediff(a.timestamp, b.timestamp) from   status_change as a
(SELECT b.timestamp from status_change as b 
 WHERE a.timestamp<b.timestamp and a.room=b.room
 ORDER BY b.timestamp DESC LIMIT 1)

Hopefully that conveys what I'm trying to accomplish.

Thanks

Was it helpful?

Solution 2

Try this (and you should put a primary key on it, especially for performance reasons)

SELECT status_change.*
 , previous.timestamp AS earlier_timestampe
 , TIMEDIFF(status_change.timestamp, previous.timestamp) AS time_between
FROM status_change 
LEFT JOIN status_change AS previous
  ON status_change.room = previous.room
    AND status_change.timestamp > previous.timestamp
LEFT JOIN status_change AS inbetweener
  ON status_change.room = inbetweener.room
    AND inbetweener.timestamp BETWEEN previous.timestamp AND status_change.timestamp
WHERE inbetweener.room IS NULL
ORDER BY status_change.timestamp DESC;

OTHER TIPS

SELECT t2.timestamp-t1.timestamp 
FROM state_change AS t1 
JOIN (SELECT * FROM state_change) AS t2 
ON t1.new_state = t2.prev_state AND t1.timestamp < t2.timestamp

Aside from the queries that are offered, I would strongly suggest adding a simple trigger based on the add of each new entry per device. Basically two columns lastUpdateID, UpdateIDBeforeThat.

Then in your update trigger, do something like

update RoomTable
   set UpdateIDBeforeThat = lastUpdateID,
       lastUpdateID = newIDJustInserted
   where
      room = RoomBasedOnInsertedRecord
     and currentRoomStatus != InsertedRecordRoomStatus

Then, your query to compare could be as simple as select

select
      r.roomid,
      c1.date/time,
      c2.date/time,
      calc-diff of date/time,
      any other fields from c1 or c2 respectively
   FROM 
      rooms r
         LEFT JOIN status_change c1
            on r.lastUpdateID = c1.ID
         left join status_change c2
            on r.UpdateBeforeThat = c2.ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top