我有这个要求,但是效果不好。
select date_format(date, "%Y-%m-%d") as month,
sum(value) as total
from :table_orders_sales_commission
where date_sub(now(), interval 12 month) <= date
group by month
结果是:
2017-04-02 4.6440
2017-04-03 2.6200
如何在一个月内获得总和(4.644 + 2.62)?
答案 0 :(得分:2)
使用MONTH功能并将其作为分组使用
select MONTH(date_format(date, "%Y-%m-%d")) as month,
sum(value) as total
from :table_orders_sales_commission
where date_sub(now(), interval 12 month) <= date
group by MONTH(date_format(date, "%Y-%m-%d"))
答案 1 :(得分:2)
select date, MONTH(date) as month,
sum(value) as total
from :table_orders_sales_commission
where date_sub(now(), interval 12 month) <= date
group by month
MONTH
只会从字段中返回月份的值,您可以在进行总和计算时按月汇总
请注意,mysql中的标准日期格式已经是您想要设置的,不需要操作它,因此我删除了与date_format(date, "%Y-%m-%d")
相关的部分,但如果您有自定义日期字段掩码,则可以保留它/ p>