0

Hello i am looking for a way to make the difference between 2 rows in Mysql query

datetime             | value
2016-01-04 10:00:00  | 50 
2016-01-04 11:00:00  | 60 
2016-01-04 13:00:00  | 65

The result i m looking for is:

datetime             | value
2016-01-04 10:00:00  | 0 
2016-01-04 11:00:00  | 10 
2016-01-04 13:00:00  | 5

How can i obtain this result by php please?

1
  • Please give us your code to work with, both PHP and MySQL. Commented Apr 11, 2016 at 14:39

1 Answer 1

1

One method uses a correlated subquery. Note that this will return NULL for the first difference:

select t.*,
       (t.value -
        (select t2.value
         from t t2
         where t2.datetime < t.datetime
         order by t2.datetime desc
         limit 1
        )
       ) as diff
from t;

It is easy enough to convert the NULL to 0, but I prefer the NULL value because the previous value is not meaningful.

Sign up to request clarification or add additional context in comments.

2 Comments

Order-by is also necessary in the outer query.
Perfect ! Thanks Guys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.