Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL if previous row value is greater than current row value

Tags:

mysql

I have a table with 2 columns: date (date) and value(int). How can I write a query to output the date and either 'Up', 'Down', or 'Same' by comparing the previous date's value to the current date's value. (e.g. if 12/01/2016 has a value of 100 and 12/02/2016 has a value of 200 then the output should be 12/02/2016 Up.

like image 479
JGW Avatar asked Sep 06 '25 22:09

JGW


1 Answers

What you're looking for here is the SQL LAG() function. This will allow you to retrieve the previous entry for value, and compare to the current entry.

Using CASE, you can then assign "Up", "Down" or "Same", based on the comparison result:

SELECT date,
    CASE 
        WHEN value > LAG(value) OVER (ORDER BY date) THEN 'Up'
        WHEN value < LAG(value) OVER (ORDER BY date) THEN 'Down'
        ELSE 'Same'
    END AS change
FROM 
    table_name;
like image 122
Joseppy Avatar answered Sep 10 '25 05:09

Joseppy