DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`lungSize_generator`(vDate DATE) BEGIN SET @buildingOrder := 0; SET @route := 0; set @cajas := 0; UPDATE tmp.sorter SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 where date(created) = vDate order by routeFk, created, weight DESC; update tmp.sorter SET palletOrder = buildingOrder mod 14, lungGrow = buildingOrder mod 14 WHERE date(created) = vDate; UPDATE tmp.sorter JOIN ( SELECT routeFk, max(id) maxid FROM tmp.sorter where date(created) = vDate GROUP BY routeFk) sub ON sub.maxid = id SET lungGrow = 1 - palletOrder ; UPDATE tmp.sorter SET lungGrow = IF(palletOrder = 0, -13, lungGrow); DELETE FROM tmp.lungSize WHERE dia = vDate; INSERT INTO tmp.lungSize(dia, hora,size) select vDate,hora, @cajas := @cajas + cajas as size from ( select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0 from tmp.sorter where date(created) = vDate group by hora ) sub; SELECT * FROM tmp.lungSize WHERE dia = vDate; END$$ DELIMITER ;