Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to find the difference between successive rows in Mysql

As I am new to MySQL, this question may be silly. How can I find the difference between successive rows?
Example:
A table (tableName='Abc') contains a single row as follows,

|DATA|
|10  |
|20  |
|30  |
|40  |
|50  |

Here I want get the output as,

|Dif|
|10 |
|10 |
|10 |
|10 |

How to find the difference like this without any index (primary or Auto_increment)?

like image 252
Deepak Mani Avatar asked Mar 14 '12 06:03

Deepak Mani


People also ask

How will you compare successive rows within the same table in MySQL?

Here's the SQL query to compare each row with previous row. In the above query, we join sales table with itself using an INNER JOIN condition g2.id=g1.id + 1 that allows you to compare each row with its previous row. Please note, this condition depends on the fact that our id column has consecutive numbers.

How do you find the difference between two consecutive rows in SQL?

In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.

Can you compare rows in SQL?

One of the easiest ways, to compare this is using the lag function. The lag function will allow you to shift the rows downward so that you can view these rows as one observational row. Here is a simple example of how to use the lag function to shift rows downward.

How do I find the difference between two values in SQL?

SQL Server DIFFERENCE() Function The DIFFERENCE() function compares two SOUNDEX values, and returns an integer. The integer value indicates the match for the two SOUNDEX values, from 0 to 4. 0 indicates weak or no similarity between the SOUNDEX values.


2 Answers

A self-join is one way to compare consecutive rows:

SELECT
    MIN(T2.DATA - T1.DATA) AS Dif
FROM
    Abc T1 INNER JOIN Abc T2 on T1.DATA < T2.DATA
ORDER BY
    T1.DATA
like image 147
John Pick Avatar answered Oct 09 '22 14:10

John Pick


Use user-defined variables:

SET @prevValue:=0;
SELECT value-@prevValue AS diff,@prevValue:=value FROM t;

You'll have to discard the first row for your case.

If the table contains both value and diff fields, you can set the diff field with:

SET @prevValue:=0;
UPDATE t SET diff=IF((@d:=value-@prevValue) AND (@prevValue:=value),@d,@d);

Using the IF is the only way I could find to both set diff and update the @prevValue variable.

like image 23
Roger Dueck Avatar answered Oct 09 '22 14:10

Roger Dueck