/* CALCULATE AVERAGE BMI FOR USER WITHIN TIMESPAN */
/* =============================================================================================================== */
DROP FUNCTION IF EXISTS GET_AVERAGE_BMI;
COMMIT;

delimiter //

CREATE FUNCTION `GET_AVERAGE_BMI`(`p_userId` varchar(36), `p_start` datetime, `p_end` datetime)
RETURNS DECIMAL(10, 1)
BEGIN

	DECLARE avgBmi DECIMAL(10, 1);
	
	SET avgBmi = (
    SELECT ROUND(SUM(`bmi`)/COUNT(`bmi`) * 10) / 10
    FROM `BMIs`
    WHERE `userId` = p_userId
    AND `day` >= p_start
    AND `day` < p_end
    AND `status` NOT IN ('inactive', 'delete')
    AND `dependant` IS NULL
  );
	
	RETURN avgBmi;

END 
//
COMMIT //

delimiter ;
