Calculate percent increase/decrease from previous row value

后端 未结 5 1064
再見小時候
再見小時候 2021-01-06 16:57

I have a table that looks something like this:

|date_start  | date_end    |amount | 
+------------+-------------+-------+
|2015-02-23  | 2015-03-01  |50              


        
5条回答
  •  感动是毒
    2021-01-06 17:52

    If we assume that the previous row always ends exactly one day before the current begins (as in your sample data), then you can use a join. The percentage increase would be:

    select t.*,
           100 * (t.amount - tprev.amount) / tprev.amount
    from atable t left join
         atable tprev
         on tprev.date_end = t.date_start - interval 1 day;
    

    However, your results seem to just have the difference, which is easier to calculate:

    select t.*,
           (t.amount - tprev.amount) as diff
    from atable t left join
         atable tprev
         on tprev.date_end = t.date_start - interval 1 day;
    

提交回复
热议问题