update erpa77, 
(     SELECT erpa77.nr01 as nr01, 
            erpa77.p01  as p01, 
            erpa77.p08  as p08, 
            ifnull( ( select sum(quan)
                      from erpa76 as erpa76_in
                      where erpa76_in.p00=erpa77.p01
                      group by erpa76_in.p00), 0) as quan, 
                      
            ifnull( ( select sum(1)
                      from erpa77 as erpa77_in
                      where erpa77_in.p01=erpa77.p01
                         && erpa77_in.nr01<=erpa77.nr01
                         && erpa77_in.p08=1
                      group by erpa77_in.p01), 0) as tquan 
     FROM erpa77
     where p08=1       
) as tbl01
set erpa77.p08=0, 
    erpa77.remdate=curdate(), 
    erpa77.remtime=curtime()
where erpa77.nr01=tbl01.nr01
   && tbl01.quan<tbl01.tquan;
/*peg_end*/   
    
             