calculate the differences between two rows in SQL

前端 未结 3 713
暖寄归人
暖寄归人 2021-01-03 12:21

I have a SQL table, one row is the revenue in the specific day, and I want to add a new column in the table, the value is the incremental (could be positive or negative) rev

3条回答
  •  Happy的楠姐
    2021-01-03 12:58

    If you're okay with re-ordering the columns slightly, something like this is pretty simple to understand:

    SET @prev := 0;
    SELECT day, revenue - @prev AS diff, @prev := revenue AS revenue
    FROM revenue ORDER BY day ASC;
    

    The trick is that we calculate the difference to the previous first, then set the previous to the current and display it as the current in one step.

    Note, this depends on the order being correct since the calculations are done during the returning of the rows, so you need to make sure you have an ORDER BY clause that returns the days in the correct order.

提交回复
热议问题