DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`facturacion_media_anual_update`() BEGIN TRUNCATE TABLE bs.clientAnnualConsumption; REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) SELECT clientFk, avg(Facturacion) FROM ( SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion FROM vn.invoiceOut WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) GROUP BY clientFk, year, month ) vol GROUP BY clientFk; END$$ DELIMITER ;