I would like help with mysql query that refers to the cell above.
for example, in the following table:
primary key(id) day count percentage change
1 monday 1 0
2 tuesday 2 (1-0)*100%=100%
3 wednesday 5 (2-1)*100%=100%
4 thursday 9 (5-2)*100%=300%
5 friday 27 (9-5)*100%=400%
The percentage change results are based on the results of the previous two days of the count column. Is there a way to incorporate the primary key(id) to refer to the cells “above”?
There is not an easy way. You need to use a self join.
The
left outer joinmakes sure all the original rows stay, even when there are not preceding ids.This works because the ids are sequential. If the ids are not sequential, and the counts are monotonically increasing, you can do this with correlated subqueries:
Note: this will not work correctly if two values are the same in a row. For that, you would need to use the id instead:
If the counts are not increasing, then you have to get the ids, and join in the values again. What fun! Here is the code: