原本的SQL和查出的结果如下:
SELECT
biz_day,
record.amount
FROM
ods_sale_pay_record record
WHERE
project.delete_flag = 'N'
AND ( record.biz_day >= '2021-10-01' AND record.biz_day <= '2021-10-31'
OR record.biz_day >= '2022-01-01' AND record.biz_day <= '2022-01-31')
结果:
文章图片
现要求按照月份为维度汇总数据,可以使用DATE_FORMAT函数
修改后的SQL如下:
SELECT
DATE_FORMAT(biz_day,'%Y%m') months,
SUM( record.amount ) 'amount'
FROM
ods_sale_pay_record record
WHERE
record.status_code = 'PAY_RECORD_PAID'
AND ( record.biz_day >= '2021-10-01' AND record.biz_day <= '2021-10-31'
OR record.biz_day >= '2022-01-01' AND record.biz_day <= '2022-01-31')
GROUP BY
record.biz_day
结果如下:
文章图片
【mysql 把date类型数据查出来后按周,按月分组】拓展:
如果想要按照天、周、月等不同的粒度对数据进行分组统计也可以参考如下的语法:
1)按天统计:select DATE_FORMAT(biz_day,'%Y%m%d') days,SUM( record.amount ) 'amount' from test group by biz_day;
2)按周统计:select DATE_FORMAT(biz_day,'%Y%u') weeks,SUM( record.amount ) 'amount' from test group by biz_day;
3)按月统计:select DATE_FORMAT(biz_day,'%Y%m') months,SUM( record.amount ) 'amount' from test group by biz_day;
推荐阅读
- mysql|InnoDB数据页结构
- javaweb|基于Servlet+jsp+mysql开发javaWeb学生成绩管理系统
- mysql|一文深入理解mysql
- Java毕业设计项目实战篇|Java项目:在线嘿嘿网盘系统设计和实现(java+Springboot+ssm+mysql+maven)
- SQL|SQL基本功(五)--函数、谓词、CASE表达式
- vue|电商后台管理系统(vue+python|node.js)
- Java及基础算法及数据结构|旧笔记整理(MySQL)
- mysql|双非本211硕,无实习无项目,自学大数据开发,秋招上岸
- 数据库|Mysql--InnoDB存储引擎详解
- MySQL学习笔记-9-order by