MySQL中按時間統計是一個非常常見的需求,尤其是在數據分析和業務監控等領域。下面我們來介紹一些關于MySQL中按時間統計的SQL語句。
1. 按天統計
SELECT DATE_FORMAT(create_time,'%Y-%m-%d') AS stats_date, COUNT(*) AS cnt FROM table_name GROUP BY stats_date;
2. 按周統計
SELECT CONCAT(DATE_FORMAT(DATE_SUB(create_time, INTERVAL WEEKDAY(create_time) DAY),'%Y-%m-%d'),'~',DATE_FORMAT(DATE_ADD(create_time, INTERVAL 6-WEEKDAY(create_time) DAY),'%Y-%m-%d')) AS stats_date, COUNT(*) AS cnt FROM table_name GROUP BY WEEK(create_time);
3. 按月統計
SELECT DATE_FORMAT(create_time,'%Y-%m') AS stats_date, COUNT(*) AS cnt FROM table_name GROUP BY stats_date;
4. 按小時統計
SELECT CONCAT(DATE_FORMAT(create_time,'%Y-%m-%d %H'),':00:00~',DATE_FORMAT(create_time,'%Y-%m-%d %H'),':59:59') AS stats_date, COUNT(*) AS cnt FROM table_name GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d %H');
5. 按分鐘統計
SELECT CONCAT(DATE_FORMAT(create_time,'%Y-%m-%d %H:%i'),':00~',DATE_FORMAT(create_time,'%Y-%m-%d %H:%i'),':59') AS stats_date, COUNT(*) AS cnt FROM table_name GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d %H:%i');
以上就是MySQL中按時間統計的五種常用方式,用于各種應用場景。如今,MySQL的時間統計功能已經越來越成熟,具有豐富的功能,可根據業務需求選擇使用。