DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`porfolio_add`() BEGIN /** * Inserta en la tabla @bs.portfolio las ventas desde el año pasado * agrupadas por equipo, año y mes */ DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; CALL util.time_generate( MAKEDATE(vYear, 1), (SELECT MAX(dated) FROM sale) ); INSERT INTO portfolio(yeared, monthed , saleDepartmentFk, Amount) SELECT t.`year`, t.`month`, w.code, SUM(s.amount) FROM tmp.time t JOIN sale s on t.dated = s.dated JOIN vn.client c on c.id = s.clientFk JOIN vn.department d ON d.id = c.salesDepartmentFk GROUP BY d.id, t.`year`, t.`month`; DROP TEMPORARY TABLE tmp.time; END$$ DELIMITER ;