DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT) BEGIN DECLARE vStarted DATE; DECLARE vEnded DATETIME; SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded FROM `time` t WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period; SELECT t.shipped, w.name warehouse, s.ticketFk, t.nickname client, am.name agencyName, wk.code salesPerson, s.itemFk, IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, s.quantity, s.price, s.priceFixed, s.discount, tls.name stateName, sb.buyFk, s.id saleFk, wk.id salesPersonFk FROM sale s JOIN ticket t ON t.id = s.ticketFk JOIN warehouse w ON w.id = t.warehouseFk JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id LEFT JOIN saleBuy sb ON sb.saleFk = s.id LEFT JOIN buy b ON b.id = sb.buyFk LEFT JOIN item ig ON ig.id = b.itemOriginalFk WHERE s.itemFk = vItemFk AND t.shipped BETWEEN vStarted AND vEnded AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk) ORDER BY t.shipped, t.id; END$$ DELIMITER ;