-- 创建表结构
DROP TABLE IF EXISTS `group_test`;
create table group_test
(
id varchar(36) not null primary key,
name varchar(128) not null comment 'name',
count int default 0 comment 'count',
create_time timestamp default CURRENT_TIMESTAMP comment 'createTime'
) comment '分组测试';
-- 造数据
insert into group_test
values (1, 'name1', round(rand()*100), now() - interval 1 month);
insert into group_test
values (2, 'name2', round(rand()*100), now() - interval 2 month);
insert into group_test
values (3, 'name3', round(rand()*100), now() - interval 3 month);
insert into group_test
values (4, 'name4', round(rand()*100), now() - interval 4 month);
insert into group_test
values (5, 'name5', round(rand()*100), now() - interval 5 month);
insert into group_test
values (6, 'name6', round(rand()*100), now() - interval 6 month);
insert into group_test
values (7, 'name7', round(rand()*100), now() - interval 7 month);
insert into group_test
values (8, 'name8', round(rand()*100), now() - interval 8 month);
insert into group_test
values (9, 'name9', round(rand()*100), now() - interval 9 month);
-- 查询sql,这里将会查询最近六个月的数据,并且计算得出每个月的总和
select concat(date_format(date,'%m'),'月') as month, ifnull(sum(b.count), 0) as sum
from (SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH AS date
UNION ALL
SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 2 MONTH
UNION ALL
SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 3 MONTH
UNION ALL
SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 4 MONTH
UNION ALL
SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 5 MONTH
UNION ALL
SELECT LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 6 MONTH) a
left join
group_test b on a.date = LAST_DAY(b.create_time) + INTERVAL 1 DAY - INTERVAL 1 MONTH
group by a.date
在解决该问题的过程中,发现date_sub(),date_add() 可以使用运算符'+','-'进行替换,
但是在使用时并不放心是否是优雅的使用方式,于是查询了 mysql8.0参考手册 ,并且
在文档中找到相关的介绍,文档中明确的表示是可以使用运算符进行替换的。
网友评论