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

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

ont sql 數據 過程 %x tail art bar 變量

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

[html] view plain copy
  1. CREATE PROCEDURE developer_count
  2. (
  3. searchType int,
  4. startTime varchar(64),
  5. endTime varchar(64)
  6. )
  7. BEGIN
  8. /*定義變量天數*/
  9. declare day_num int;
  10. if searchType = 1 then
  11. /*本周數據查詢*/
  12. 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;
  13. end if;
  14. if searchType = 2 then
  15. /*本月數據查詢*/
  16. 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;
  17. end if;
  18. if searchType = 3 then
  19. /*最近三個月數據查詢*/
  20. 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;
  21. end if;
  22. if searchType = 4 then
  23. /*按月份進行數據統計*/
  24. select datediff(startTime, endTime) into day_num;
  25. if day_num <=7 then
  26. 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;
  27. end if;
  28. if day_num >7 && day_num <= 30 then
  29. 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;
  30. end if;
  31. if day_num >30 && day_num <= 90 then
  32. 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;
  33. end if;
  34. end if;
  35. end;

調用存儲過程方法

CALL DEVELOPER_COUNT(1,‘2016-06-07‘,‘2016-06-16‘);調用存儲過程

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