简体   繁体   中英

Compute column value depending on values in preceding row

(DB: MySQL 5)

I have a table named "data" with the following structure:

timestamp    value    delta
1234535853   12
1234535934   64
1234536700   22

The delta column is not set, and I want to set it to

delta(n) = (value(n) - value(n-1)) / (timestamp(n) - timestamp(n-1))

where n is the respective row number (I do not have a row number index, though! The "preceding row" is the row with the next lower timestamp, since (according to my research) MySQL does not support a ROWNUM construct).

The task is thus to compute a sort of "finite difference" between successive rows. I have read about subqueries and think they might be the way to go somehow, but was unsuccessful in creating one that accomplishes the task. What would be the best way to go about it?

use

SELECT A.timestamp, A.value, ((A.value - D.value) / (A.timestamp - A.prevtimestamp)) AS delta
FROM
(SELECT X.timestamp, X.value, (SELECT MAX (S.timestamp) FROM data S WHERE S.timestamp < X.timestamp) AS prevtimestamp FROM data X ) A, data D WHERE D.timestamp = A.prevtimestamp
ORDER BY A.timestamp DESC

BEWARE:

Since you don't give much detail about the table structure etc. the above query will fail if timestamp is not unique.

BTW you should consider using other column names as these are prone to getting into trouble (reserved...).

EDIT - regarding performance:

The above query would be much faster if you create an unique index on the timestamp column!

this should work:

SELECT
  timestamp,
  value,
  (
   (value - (SELECT value FROM data WHERE timestamp < d.timestamp ORDER BY timestamp DESC LIMIT 1))
    /
   (timestamp - (SELECT timestamp FROM data WHERE timestamp < d.timestamp ORDER BY timestamp DESC LIMIT 1))
  ) AS delta
FROM
  data AS d
ORDER BY
  timestamp

in the subselects i'm simply ordering by timestamp backwards where the timestamp is lower than the one of the current row. limiting this to 1 entry gives me the preceding row. i have to do this two times to get the value and the timestamp - the rest is simple math with the formula you've given.

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