DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() BEGIN REPLACE bs.waste SELECT YEAR(t.shipped), WEEK(t.shipped, 4), it.workerFk, it.id, s.itemFk, SUM(s.quantity), SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) value, SUM ( IF( a.nickname IN ( 'MERMA: FALTAS', 'MERMA: CONTENEDOR', 'MERMA: TRANSPORTE/OTROS' ), (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) ) internalWaste, SUM ( IF( a.nickname IN ( 'MERMA: RECLAMACION BASURA', 'MERMA: RECLAMACION TALLER', 'MERMA: RECLAMACION FALTAS' ), (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) ) externalWaste FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.ticket t ON t.id = s.ticketFk STRAIGHT_JOIN vn.address a ON a.id = t.addressFk JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = w.id JOIN vn.buy b ON b.id = lb.buy_id WHERE w.isManaged AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) GROUP BY it.id, s.itemFk; END$$ DELIMITER ;