CREATE PROCEDURE VisitTrendReportCount(@customerparam INT, @scheduleparam INT, @grouptypeparam INT, @fromparam DATETIME, @toparam DATETIME)
    AS
BEGIN

DECLARE @QRY NVARCHAR(MAX),@periodBASE VARCHAR(200);


IF @grouptypeparam = 1
    SET @periodBASE = ' CONVERT(DATE,DATEADD(DAY,(DATEDIFF(DAY,@fromparam, cloud_date) / 7)* 7,@fromparam)) AS period  ' ;
ELSE IF @grouptypeparam = 2
    SET @periodBASE = ' CONVERT(DATE,DATEADD(MONTH,(DATEDIFF(MONTH,@fromparam,cloud_date)),@fromparam)) AS period  ';
ELSE IF @grouptypeparam = 3
    SET @periodBASE = ' CONVERT(DATE, @fromparam) AS period ';
ELSE
    SET @periodBASE = 'CONVERT(DATE,cloud_date) AS period ';



SET @QRY = CONCAT(

'
SELECT
	COUNT(*)
FROM
	(
	SELECT
		*
	FROM
		(
		SELECT ' ,
			@periodBASE ,
		' FROM
			cloud_date_table PC
		WHERE
			PC.cloud_date BETWEEN @fromparam AND @toparam

    ) AS BASE
	GROUP BY
		period) AS BASE

'
);


DECLARE @parameterDefinition NVARCHAR(4000);
SET @parameterDefinition = N'@customerparam INT, @scheduleparam INT, @grouptypeparam INT, @fromparam DATETIME, @toparam DATETIME';
EXEC sp_executesql @QRY ,@parameterDefinition, @customerparam=@customerparam, @scheduleparam=@scheduleparam, @grouptypeparam=@grouptypeparam, @fromparam=@fromparam, @toparam=@toparam;

END