MySQL中的date_format单行函数的使用

先建立如下时间表: 

create table orders(
id int(11),
money double(5,2),
create_time timestamp
)

INSERT INTO `orders` VALUES (1, 10.00, '2019-08-16 15:45:24');
INSERT INTO `orders` VALUES (2, 10.00, '2019-05-01 15:45:40');
INSERT INTO `orders` VALUES (3, 10.00, '2019-03-01 15:45:57');
INSERT INTO `orders` VALUES (4, 10.00, '2019-07-18 15:46:13');
INSERT INTO `orders` VALUES (5, 10.00, '2019-05-08 15:46:33');
INSERT INTO `orders` VALUES (6, 10.00, '2018-10-01 15:47:10');

MySQL中的date_format单行函数的使用_第1张图片

假设这是一张2019年和2018两年的支出表,要按一定的时间间隔来统计支出,应该如何查询呢?

这里就需要用到date_format函数来将时间类型的数据转换为字符串类型,这样就可以按照字符串进行分类了。

1.统计每年的支出:

select date_format(create_time,'%Y'),sum(money) from orders group by date_format(create_time,'%Y');

将时间类型的数据进行转换的时候只转换其中的年份,这样再分组,就可以按照年份来分类了:

2.统计每月的支出:

select date_format(create_time,'%Y%m'),sum(money) from orders group by date_format(create_time,'%Y%m');

 和上题一个道理,只不过这次要转换成年份和月份:

 MySQL中的date_format单行函数的使用_第2张图片

 

 

你可能感兴趣的:(MySQL中的date_format单行函数的使用)