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 表 替換成你自己構造的順序序列表中間表即可。

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM