Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere il nuovo saldo corrente dal saldo esistente?

Un Case statement può gestire la tua condizione.

SELECT id ID, token TK, actual_pay PAY,
       IF(@rtp IS NULL, @rtp:=token, @rtp:[email protected]+actual_pay) RTP,
       IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected]) BAL,

       (case IF(@rtp IS NULL, @rtp:=token, @rtp:[email protected]+actual_pay)
         when IF(@rtp IS NULL, @rtp:=token, @rtp:[email protected]+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:[email protected])
        when IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected]) <= 
             (select token from token_table where id = a.id+1)
        then 0
       else 
        IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected]) - 
        (select token from token_table where id = a.id+1)
      end case) nbal,

      (case IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected])
        when IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected]) <= 
             (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:[email protected])
       else 
        IF(@bal IS NULL, @bal:=actual_pay-token, @bal:[email protected]) - 
        (select token from token_table where id = a.id+1)
      end case) ntk

FROM token_table a
JOIN (SELECT @rtp:=NULL, @bal:=NULL) b;