ITPub博客

首页 > 数据库 > MySQL > 查看每个月举办的活动总数

查看每个月举办的活动总数

原创 MySQL 作者:壹頁書 时间:2015-12-11 11:09:58 0 删除 编辑
现在写这种SQL纯属是小娱乐了.不过这种场景貌似挺多的.还是需要记录一下.

实验结构和数据:
  1. create table act(  
  2.     id int primary key auto_increment,  
  3.     name varchar(10),  
  4.     starttime timestamp not null,  
  5.     endtime timestamp not null  
  6. );  
  7.   
  8. INSERT INTO `act` (`id`,`name`,`starttime`,`endtime`) VALUES (1,'活动一','2015-01-01 00:00:00','2015-05-01 00:00:00');  
  9. INSERT INTO `act` (`id`,`name`,`starttime`,`endtime`) VALUES (2,'活动二','2015-02-01 00:00:00','2015-03-01 00:00:00');  
  10. INSERT INTO `act` (`id`,`name`,`starttime`,`endtime`) VALUES (3,'活动三','2015-05-01 00:00:00','2015-10-01 00:00:00');  
  11. INSERT INTO `act` (`id`,`name`,`starttime`,`endtime`) VALUES (4,'活动四','2015-08-01 00:00:00','2015-11-01 00:00:00');  

需求:
查看每个月举办的活动总数.
以活动一为例,开始时间是2015-01-01,结束时间是2015-05-01
那么该活动在1月,2月,3月,4月,5月各算一次.

这个需求本质是把一个时间的范围,变成具体的记录
比如有一行 6月-9月
变成4行
6月
7月
8月
9月

这个肯定需要数字辅助表的介入了.
创建数字辅助表
  1. create table nums(id int not null primary key);  
  2.   
  3. delimiter $$  
  4. create procedure pCreateNums(cnt int)  
  5. begin  
  6.     declare s int default 1;  
  7.     truncate table nums;  
  8.     while s<=cnt do  
  9.         insert into nums select s;  
  10.         set s=s+1;  
  11.     end while;  
  12. end $$  
  13. delimiter ;  
  14.   
  15. call pCreateNums(1000);  

统计SQL:
  1. select ts,count(*) from (  
  2.     select a.*,date_format(a.starttime+interval id-1 month,'%Y-%m-%d') ts from (  
  3.         select name,starttime,endtime,extract(YEAR_MONTH from endtime)-extract(YEAR_MONTH from starttime)+1 inter from act   
  4.     ) a,nums  
  5.     where nums.id<=a.inter  
  6. ) b group by ts;  

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1870300/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 好友推荐问题
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339966