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

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:

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:

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:

Or:

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

See the demo.

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