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

delimiter //

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

	DECLARE avgSystolic int;
	
	SET avgSystolic = (
    SELECT ROUND(SUM(`systolic`)/COUNT(`systolic`))
    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 avgSystolic;

END 
//
COMMIT //

delimiter ;
