DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`agencyVolume`() BEGIN /** * Calculates and presents information on shipment and packaging volumes * for agencies that are not owned for a specific period. */ DECLARE vStarted DATETIME DEFAULT util.VN_CURDATE(); DECLARE vEnded DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); SELECT ag.id agency_id, CONCAT(RPAD(c.name, 16,' _') ,' ',ag.name) Agencia, COUNT(*) expediciones, SUM(t.packages) Bultos, SUM(tpe.boxes) Faltan FROM ticket t JOIN warehouse w ON w.id = t.warehouseFk JOIN country c ON w.countryFk = c.id JOIN address a ON a.id = t.addressFk JOIN agencyMode am ON am.id = t.agencyModeFk JOIN agency ag ON ag.id = am.agencyFk JOIN ( SELECT sv.ticketFk, CEIL(1000 * SUM(sv.volume) / vc.standardFlowerBox) boxes FROM ticket t JOIN saleVolume sv ON sv.ticketFk = t.id JOIN volumeConfig vc WHERE t.shipped BETWEEN vStarted AND vEnded AND (t.packages IS NULL OR NOT t.packages) GROUP BY t.id ) tpe ON tpe.ticketFk = t.id WHERE t.shipped BETWEEN vStarted AND vEnded AND NOT ag.isOwn GROUP BY ag.id ORDER BY Agencia; END$$ DELIMITER ;