CREATE PROCEDURE VisitTrendReportCount(IN customerparam INT, IN scheduleparam INT, IN grouptypeparam INT, IN fromparam DATETIME, IN toparam DATETIME)
BEGIN
SET @customerparam = customerparam;
SET @scheduleparam = scheduleparam;
SET @grouptypeparam = grouptypeparam;
SET @fromparam = fromparam;
SET @toparam = toparam;


IF grouptypeparam = 1 THEN
    SET @periodBASE = " DATE(DATE_ADD(@fromparam, INTERVAL ( DATEDIFF( cloud_date, @fromparam) DIV 7)*7 DAY)) AS period  " ;
ELSEIF grouptypeparam = 2 THEN
    SET @periodBASE = " DATE(DATE_ADD(@fromparam, INTERVAL TIMESTAMPDIFF(MONTH, @fromparam ,cloud_date) MONTH )) as period  ";
ELSEIF grouptypeparam = 3 THEN
    SET @periodBASE = " DATE(DATE_ADD(@fromparam, INTERVAL ( DATEDIFF( cloud_date, @fromparam) DIV @daydifference)*@daydifference DAY)) AS period ";
ELSE
    SET @periodBASE = " DATE(cloud_date) AS period ";
END IF;

SET @QRY = CONCAT("

SELECT
    COUNT(*)
FROM
    (
        SELECT ",
            @periodBASE,
" FROM
			cloud_date_table PC
WHERE
    PC.cloud_date BETWEEN @fromparam AND @toparam
GROUP BY
    period
    ) AS BASE

"
);

PREPARE stmt FROM @QRY;
EXECUTE stmt;
DEALLOCATE  PREPARE stmt;
END