MySQL按分/時/天/周/月/季度/半年/年分組

EHEKUDA發表於2020-11-27

定義和用法

DATE_FORMAT() 函式用於以不同的格式顯示日期/時間資料。

語法

DATE_FORMAT(date, format)

date 引數是合法的日期。format 規定日期/時間的輸出格式。

常用 format 格式:

%d天,數值(00-31)
%m月,數值(00-12)
%Y年,4 位
%H小時(00-23)
%i分鐘,數值(00-59)
%s秒(00-59)

詳細介紹:MySQL DATE_FORMAT() 函式

1. 精確到分鐘分組

SELECT count( id ), DATE_FORMAT( date, '%Y-%m-%d %H:%i' ) FROM test_table GROUP BY DATE_FORMAT( date, '%Y-%m-%d %H:%i' ) ORDER BY DATE_FORMAT( date, '%Y-%m-%d %H:%i' ) DESC;

2. 精確到小時分組

SELECT count( id ), DATE_FORMAT( date, '%Y-%m-%d %H' ) FROM test_table GROUP BY DATE_FORMAT( date, '%Y-%m-%d %H' ) ORDER BY DATE_FORMAT( date, '%Y-%m-%d %H' ) DESC;

3. 精確到日期分組

SELECT count( id ), DATE_FORMAT( date, '%Y-%m-%d' ) FROM test_table GROUP BY DATE_FORMAT( date, '%Y-%m-%d' ) ORDER BY DATE_FORMAT( date, '%Y-%m-%d' ) DESC;

4. 精確到周分組(星期一為每週第一天)

SELECT count( id ), DATE_FORMAT( date, '%x-%v' ) FROM test_table GROUP BY DATE_FORMAT( date, '%x-%v' ) ORDER BY DATE_FORMAT( date, '%x-%v' ) DESC;

5. 精確到月份分組

SELECT count( id ), DATE_FORMAT( date, '%Y-%m' ) FROM test_table GROUP BY DATE_FORMAT( date, '%Y-%m' ) ORDER BY DATE_FORMAT( date, '%Y-%m' ) DESC;

6. 精確到季度分組

SELECT count( id ), SUBSTR( date, 1, 4 ), QUARTER ( date ) FROM test_table GROUP BY SUBSTR( date, 1, 4 ), QUARTER ( date ) ORDER BY SUBSTR( date, 1, 4 ) DESC, QUARTER ( date ) DESC;

7. 精確到半年分組

SELECT count( id ), yearVal, label FROM ( SELECT id, SUBSTR( date, 1, 4 ) AS 'yearVal', CASE WHEN SUBSTR( date, 6, 2 ) < 7 THEN '上半年' ELSE '下半年' END AS 'label' FROM test_table ) tmp GROUP BY yearVal, label ORDER BY yearVal DESC, label ASC;

8. 精確到年份分組

SELECT count( id ), DATE_FORMAT( date, '%Y' ) FROM test_table GROUP BY DATE_FORMAT( date, '%Y' ) ORDER BY DATE_FORMAT( date, '%Y' ) DESC;

相關文章