DROP PROCEDURE IF EXISTS `bs`.`weekWaste_byWorker`;

DELIMITER $$
$$
CREATE
    DEFINER = root@`%` PROCEDURE `bs`.`weekWaste_byWorker__`(IN vWorkerFk INT)
BEGIN

    DECLARE vWeek INT;
    DECLARE vYear INT;

    SELECT week, year
    INTO vWeek, vYear
    FROM vn.time
    WHERE dated = TIMESTAMPADD(WEEK, -1, CURDATE());

    SELECT *, 100 * mermas / total AS porcentaje
    FROM (
        SELECT ws.family,
               SUM(ws.saleTotal) AS total,
               SUM(ws.saleWaste) AS mermas
        FROM bs.waste ws
            JOIN vn.worker w ON w.user = ws.buyer
        WHERE year = vYear
          AND week = vWeek
          AND w.id = vWorkerFk
        GROUP BY family
    ) sub
    ORDER BY porcentaje DESC;
END;;$$
DELIMITER ;

