1. 程式人生 > >mysql 內建功能 函式 date_format函式

mysql 內建功能 函式 date_format函式

 

 

建立資料庫db12

create database db12 charset=utf8;
use db12;

 

準備表和記錄
CREATE TABLE blog (
    id INT PRIMARY KEY auto_increment,
    NAME CHAR (32),
    sub_time datetime
);

 

插入記錄

INSERT INTO blog (NAME, sub_time)
VALUES
    ('第1篇','2015-03-01 11:31:21'),
    ('
第2篇','2015-03-11 16:31:21'), ('第3篇','2016-07-01 10:21:31'), ('第4篇','2016-07-22 09:23:21'), ('第5篇','2016-07-23 10:11:11'), ('第6篇','2016-07-25 11:21:31'), ('第7篇','2017-03-01 15:33:21'), ('第8篇','2017-03-01 17:32:21'), ('第9篇','2017-03-01 18:31:21');

 

提取sub_time欄位的值,按照格式後的結果即"年月"來分組
mysql>
select date_format(sub_time,'%Y-%m'),count(id) from blog group by date_format(sub_time,'%Y-%m'); +-------------------------------+-----------+ | date_format(sub_time,'%Y-%m') | count(id) | +-------------------------------+-----------+ | 2015-03 | 2 | | 2016-07 |
4 | | 2017-03 | 3 | +-------------------------------+-----------+ 3 rows in set (0.00 sec)