[英]How to select from mysql that group by month in one year and sum value in a month?
received_amount | updated_at
----------------------------
4000 | 2020-11-02
2000 | 2020-11-03
1000 | 2020-12-02
1000 | 2020-12-04
3000 | 2021-01-02
2000 | 2020-01-02
这是我的名为“ payment ”的数据库表,其结构和数据。
现在我想在我的 php web 页面中显示类似下面提到的表格数据,当用户 select 使用日历中的年份时(我已经使用 Zebra 日期选择器) Zebra 日期选择器给出年份。
在这种情况下,用户 select 是 2020 年,它应该显示如下值。
Year | Month | Monthly Total
----------------------------
2020 | November| 6000
2020 | December| 2000
您可以在查询中像这样使用 group by
GROUP BY EXTRACT(YEAR FROM updated_at), EXTRACT(MONTH FROM updated_at)
然后像这样 select
SELECT EXTRACT(YEAR FROM updated_at) as Year,
EXTRACT(MONTH FROM updated_at) as Month,
SUM(received_amount) as Monthly_Total
你可以做:
select year, month, monthly_total
from (
select
extract(year from updated_at) as year,
extract(month from updated_at) as m,
monthname(updated_at) as month,
sum(receive_amount) as monthly_total
from t
where extract(year from updated_at) = 2020
group by year, month, m
) x
order by year, m
结果:
year month monthly_total
----- --------- -------------
2020 January 2000
2020 November 6000
2020 December 2000
请参阅DB Fiddle上的运行示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.