mysql 构造连续的日期

 

需求,我想以 年-月-日的格式,统计自 2019-08-20日 前10天的记录数,如果该天没有任何一条记录,则给予0

原始数据-》我想要的结果集数据

   ==============》

 

 

 

 

1、测试数据

drop table  if exists test2;
create table test2(id int primary key auto_increment,curr_date datetime);
insert into test2(curr_date) values('2019-08-11 10:12:30'),('2019-08-14 10:12:30'),('2019-08-16 10:12:30');
select * from test2;
 
 

 

问题1:如果我们直接格式化时间到  年-月-日 的格式,那么没有记录的天数就会被漏掉;

select date_format(curr_date,'%Y-%m-%d') as 'curr_date',
    count(id) as 'record_count' from test2 group by date_format(curr_date,'%Y-%m-%d');

结果是这样的,就没有达到我们的效果。

 

2、了解一个mysql数据库下的自带表

mysql.help_topic;
如下图,它有一个从0~657的顺序ID序列,一些短期的操作可以借助它来完成,比如生成连续的日期。
select max(help_topic_id),min(help_topic_id),count(help_topic_id) from mysql.help_topic;

 

 
 

 

 3、生成连续的日期

  (1)我们可以借助 2中的mysql.help_topic表,和一些固定的参数和时间函数配合即可

  (2)我们也可以自己构造一个临时表,构造一个足够大的id顺序序列。

    这个方法也很简单但是有点费事还要额外去生成,如果657个自增id序列已经够用推荐使用第1种(这种就不演示了,原理一样。)

-- 获取自'2019-08-20'的前10天
select date_format(date_add('2019-08-20',interval -t.help_topic_id day),'%Y-%m-%d') as 'curr_date'  
from mysql.help_topic t where t.help_topic_id<=10;
这就出来了

 

4、最终聚合,完成需求

/*
--
获取自某天开始的前10天   select date_format(date_add('2019-08-20',interval -t.help_topic_id day),'%Y-%m-%d') as 'curr_date' from mysql.help_topic t where t.help_topic_id<=10; -- 数据表根据时间 年-月-日 格式分组统计行数   select date_format(curr_date,'%Y-%m-%d') as 'curr_date',count(id) as 'record_count' from test2 group by date_format(curr_date,'%Y-%m-%d'); */ -- 最终整合 select t1.curr_date,ifnull(t2.record_count,0) as record_count from (
  
select date_format(date_add('2019-08-20',interval -t.help_topic_id day),'%Y-%m-%d') as 'curr_date'
  from mysql.help_topic t where t.help_topic_id<=10
) t1
left join (
  select date_format(curr_date,'%Y-%m-%d') as 'curr_date',count(id) as 'record_count'
  from test2 group by date_format(curr_date,'%Y-%m-%d')
) t2
on t1.curr_date=t2.curr_date order by t1.curr_date

最终聚合结果如下左图,数据表聚合如下右图,构造连续日期如下中间图
    

 

 
 

 如果自己构造中间表,只是把 mysql.help_topic 表 替换成你自己构造的顺序序列表中间表即可。

  

 

转载于:https://www.cnblogs.com/gered/p/11345713.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值