/* CALCULATE AVERAGE SYSTOLIC FOR USER WITHIN TIMESPAN */
/* =============================================================================================================== */
DROP FUNCTION IF EXISTS GET_AVERAGE_DIASTOLIC;
COMMIT;

delimiter //

CREATE FUNCTION `GET_AVERAGE_DIASTOLIC`(`p_userId` varchar(36), `p_start` datetime, `p_end` datetime)
RETURNS INT
BEGIN

	DECLARE avgDiastolic int;
	
	SET avgDiastolic = (
    SELECT ROUND(SUM(`diastolic`)/COUNT(`diastolic`))
    FROM `BloodPressures`
    WHERE `userId` = p_userId
    AND `day` >= p_start
    AND `day` < p_end
    AND `status` NOT IN ('inactive', 'delete')
    AND `dependant` IS NULL
  );
	
	RETURN avgDiastolic;

END 
//
COMMIT //

delimiter ;
