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

DELIMITER $$
$$
CREATE DEFINER = `root`@`%` PROCEDURE `bs`.`weekWaste__`()
BEGIN
    DECLARE vWeek INT;
    DECLARE vYear INT;

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

    SELECT *, 100 * dwindle / total AS percentage
    FROM (
        SELECT buyer,
               SUM(saleTotal) AS total,
               SUM(saleWaste) AS dwindle
        FROM bs.waste
        WHERE year = vYear
          AND week = vWeek
        GROUP BY buyer
    ) sub
    ORDER BY percentage DESC;
END;$$
DELIMITER ;

