1. 程式人生 > >MySQL 基於儲存過程 實現資料統計按日、周、月份統計模板

MySQL 基於儲存過程 實現資料統計按日、周、月份統計模板

儲存過程developer_count 是根據傳入引數searchType 決定是使用那種查詢方式,本儲存過程中包含的其他的引數是{起始時間:startime,結束時間:endtime}

CREATE PROCEDURE developer_count
(
  searchType int,
	startTime varchar(64),
	endTime varchar(64)
)
BEGIN
	/*定義變數天數*/
  declare day_num int;

  if searchType = 1 then 
  /*本週資料查詢*/
   select count(d.acct_id),d.acct_old_time from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(d.acct_old_time) GROUP BY d.acct_old_time;
	end if;
  if searchType = 2 then
	/*本月資料查詢*/
		select count(d.acct_id),d.acct_old_time from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(d.acct_old_time) GROUP BY d.acct_old_time;
  end if;
  if searchType = 3 then
	/*最近三個月資料查詢*/
		select count(d.acct_id), DATE_FORMAT(d.acct_old_time,'%x年-第%v周') as weeks from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL 90 DAY) <= date(d.acct_old_time) GROUP BY weeks;
  end if;
  if searchType = 4 then
	/*按月份進行資料統計*/
		select datediff(startTime, endTime) into day_num;
		if day_num <=7 then
				select count(d.acct_id),d.acct_old_time from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL day_num DAY) <= date(d.acct_old_time) GROUP BY d.acct_old_time;
		end if;
		if day_num >7  && day_num <= 30 then
				select count(d.acct_id),d.acct_old_time from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL day_num DAY) <= date(d.acct_old_time) GROUP BY d.acct_old_time;
		end if;
		if day_num >30 && day_num <= 90 then
				select count(d.acct_id), DATE_FORMAT(d.acct_old_time,'%x年-第%v周') as weeks from developer d where  1=1 and DATE_SUB(CURDATE(), INTERVAL day_num DAY) <= date(d.acct_old_time) GROUP BY weeks;
		end if;		
	end if;

end;

呼叫儲存過程方法

CALL DEVELOPER_COUNT(1,'2016-06-07','2016-06-16');呼叫儲存過程