Table stock_log. For each row show the most recent earlier non-zero qty of the same SKU as last_nonzero.
stock_log
qty
last_nonzero
Each hint gives a little more help. Try on your own first.
Run your code to see the output here.