mysql 按年度、季度、月度、周、日SQL統計查詢

 表結構:mysql

 表中數據總條數:2926sql

1. 統計天天的單數數據庫

  SELECT COUNT(*),DATE_FORMAT(t.create_time,'%Y-%m-%d') from t_call_record t GROUP BY DATE_FORMAT(t.create_time,'%Y-%m-%d')  (執行時間:0.003s)測試

   SELECT count(*),DATE_FORMAT(t.create_time,'%Y-%m-%d') from t_call_record t GROUP BY TO_DAYS(t.create_time)  (執行時間:0.002s).net

第二種優於第一種,會列出全部的單子3d

1.2 統計上個月的天數據blog

SELECT count(*),DATE_FORMAT(t.create_time,'%Y-%m-%d') from t_call_record t where YEAR(t.create_time) = '2018' GROUP BY DAY(t.create_time)
(執行時間:0.001s)按天統計從上個月最後一天向前推的31天數據date

1.3 按周統計數據im

SELECT count(*),WEEK(t.create_time),MONTH(t.create_time) from t_call_record t where YEAR(t.create_time) = '2018' GROUP BY WEEK(t.create_time)(執行時間:0.002s)
1.4 按月統計數據call

SELECT count(*),MONTH(t.create_time) from t_call_record t where YEAR(t.create_time) = '2018' GROUP BY MONTH(t.create_time)
(執行時間:0.002s)

1.5 按照年統計數據

SELECT count(*),YEAR(t.create_time) from t_call_record t where YEAR(t.create_time) = '2018' GROUP BY YEAR(t.create_time)(執行時間:0.001s)
1.6 按照季度統計數據

SELECT count(*),QUARTER(t.create_time) from t_call_record t where YEAR(t.create_time) = '2018' GROUP BY QUARTER(t.create_time)
(執行時間:0.001s)

1.7 查詢本年度數據

SELECT * from t_call_record t WHERE year(t.create_time) = year(curdate()) (執行時間:0.005s)

1.8 查詢本季度數據

SELECT *  from t_call_record where quater(t.create_time) = QUARTER(curdate()) (執行時間0.004s)

1.9 查詢本月度數據

SELECT * from t_call_record  where MONTH(create_time) = MONTH(CURDATE()) and year(create_time) = year(curdate())(執行時間:0.004s)

1.20 查詢本週數據

SELECT * from t_call_record t where MONTH(t.create_time) = MONTH(CURDATE()) and WEEK(t.create_time) = WEEK(CURDATE())(執行時間0.003s)

1.21 查詢近5天的記錄

SELECT * from t_call_record t where TO_DAYS(NOW())-TO_DAYS(t.create_time) <= 5(執行時間: 0.003s)

2. mysql獲取當天,昨天,本週,本月,上週,上月的起始時間
https://blog.csdn.net/qq_34775102/article/details/82776168

3. 有關現實統計的問題總結

  咱們會遇到統計數據的時候,有時候放假,在這段時間沒有進行工做,這段時間是沒有數據,咱們統計的時候想顯示數據,

 這樣就在數據庫中維護一張t_date 表:表結構以下:

DROP TABLE IF EXISTS `t_date`;
CREATE TABLE `t_date` (
  `date` date NOT NULL COMMENT '日期',
  PRIMARY KEY (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
數據截圖:


 能夠用它作關聯表查詢,讓他分組,而後left join 查詢表,實際查詢的數據,on  爲 week(t.create_time) = week(date):

某個業務列子:

  測試表,結構以下,能夠往裏面弄點測試數據

DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_no` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `weight` double DEFAULT NULL,
  `amount` double(255,0) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

查詢語句:

SELECT d.date,IFNULL(ROUND(A.total_weight,2),0), IFNULL(ROUND(A.total_amount,2),0) 
from (SELECT MIN(date) date  from t_date 
GROUP BY week(date) ) d
LEFT JOIN (
SELECT MIN(DATE_FORMAT(t.create_time,'%Y-%m-%d')) create_time,SUM(t.weight) total_weight ,
SUM(t.amount) total_amount 
from t_order t 
GROUP BY week(t.create_time) ) A
on WEEK(d.date) = WEEK(A.create_time)
ORDER BY d.date

相關文章
相關標籤/搜索