Skip to content
Advertisement

How can I calculate the highest difference of values between two immediate rows?

I have a table that follows this structure:

Table Foo

id          number
---------------------
1             5
2             8
3             3
4             67
5             1
6             10

From this table, I want to execute a SELECT that shows the number that has grown the most from one row to the immediate next one. Given this example, I would like to see as an output:

id          number
---------------------
4             67

Because the previous row (with id = 3) had a number value of 3, and the next row increased the value up to 67.

How can I do this?

Advertisement

Answer

One way to do it for your sample data is with a self join:

select f1.*
from Foo f1 inner join Foo f2
on f2.id = f1.id - 1
order by f1.number - f2.number desc limit 1

If there are gaps between the ids then you must find the previous id for each id and then retrieve the number in the previous row:

select t.id, t.number
from (
  select f1.id, f1.number, max(f2.id) previd
  from Foo f1 inner join Foo f2
  on f2.id < f1.id
  group by f1.id, f1.number
) t inner join Foo f
on f.id = t.previd
order by t.number - f.number desc limit 1

Or:

select f.*
from Foo f
order by number - (select number from Foo where id < f.id order by id desc limit 1) desc 
limit 1

For MySql 8.0+ you can use LAG() window function:

select *
from Foo
order by number - lag(number) over (order by id) desc limit 1

See the demo.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement