简体   繁体   中英

Identifying record in mysql table based on difference between two specific rows

I would really appreciate some help with a MySQL query for the following matter. My table, let's call it "data", contains the following fields: "timestamp" and "temperature". Every 30 seconds a new record is being added into it. My goal is to identify the record (timestamp) which compared to the one added 2 minutes later (4 records later) has a temperature difference of 20 degrees ( or more )

Ex.

...  
19:14:08 99
19:14:38 100
19:15:08 101
19:15:38 105
19:16:08 115
19:16:38 126
19:17:08 150
19:17:38 151
...

In this case, the timestamp which I have to find is 19:14:38, because if compared to the one at 19:16:38, we have 126-100 = 26 > 20.

There are some other conditions (not worth mentioning) which have to be met as well, but at least those I can handle myself.

Thanks for your help.

If your timestamps are exactly, you can use a self-join:

select t.*
from t join
     t tnext
     on t.timestamp = tnext.timestamp - interval 2 minutes
where tnext.temperature - t.temperature > 20;

This is highly dependent on the accuracy of your timestamps, however.

So I believe you're on the right track with a join to the same table: something like this should get you started. It's untested air-code and typically I write in oracle sql so pardon any syntax nuances...

SELECT
a.TEMPERATURE AS NEW_TEMP
,b.TEMPERATURE AS PRIOR_TEMP
FROM
DATA a
INNER JOIN DATA b ON
   b.TIMESTAMP = a.TIMESTAMP-TO_DATE('02','MM')
   AND ABS(ABS(a.TEMPERATURE) - ABS(b.TEMPERATURE)) > 20

Additionally - using a timestamp is probably not as reliable as you might think since there could be variation that you do not want to exist (such as the timestamp may be off by a second ie it is exactly 1:59 seconds prior to the new record. in which case this join would miss it. whereas if you were using an autoincremented ID as suggested above, you could simply replace that first join clause with:

b.RECORD_ID = a.RECORD_ID-4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM