Uma
Case statement
pode lidar com sua condição. SELECT id ID, token TK, actual_pay PAY,
IF(@rtp IS NULL, @rtp:=token, @rtp:=@bal+actual_pay) RTP,
IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token) BAL,
(case IF(@rtp IS NULL, @rtp:=token, @rtp:=@bal+actual_pay)
when IF(@rtp IS NULL, @rtp:=token, @rtp:=@bal+actual_pay) <=
(select token from token_table where id = a.id+1)
then 1
else 0
end case) stat,
(case IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token)
when IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token) <=
(select token from token_table where id = a.id+1)
then 0
else
IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token) -
(select token from token_table where id = a.id+1)
end case) nbal,
(case IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token)
when IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token) <=
(select token from token_table where id = a.id+1)
then
(select token from token_table where id = a.id+1) -
IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token)
else
IF(@bal IS NULL, @bal:=actual_pay-token, @bal:=@rtp-token) -
(select token from token_table where id = a.id+1)
end case) ntk
FROM token_table a
JOIN (SELECT @rtp:=NULL, @bal:=NULL) b;