简体   繁体   English

如何从 mysql 中的 select 在一年内按月分组并在一个月内求和?

[英]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

This is my database table named " payment " structured and data on it.这是我的名为“ payment ”的数据库表,其结构和数据。

Now I want to display something like below mentioned table data in my php web page when user select the year from calendar (I've use Zebra date picker for this).现在我想在我的 php web 页面中显示类似下面提到的表格数据,当用户 select 使用日历中的年份时(我已经使用 Zebra 日期选择器) Zebra date picker gives the year. Zebra 日期选择器给出年份。

In this scenario user select the year 2020 and it's should show the values as below.在这种情况下,用户 select 是 2020 年,它应该显示如下值。

Year  | Month   | Monthly Total
----------------------------
2020  | November| 6000
2020  | December| 2000

you can use group by like this in your query您可以在查询中像这样使用 group by

GROUP BY EXTRACT(YEAR FROM updated_at), EXTRACT(MONTH FROM updated_at)

and then select like this然后像这样 select

SELECT EXTRACT(YEAR FROM updated_at) as Year,
       EXTRACT(MONTH FROM updated_at) as Month,
       SUM(received_amount) as Monthly_Total

You can do:你可以做:

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

Result:结果:

 year  month     monthly_total 
 ----- --------- ------------- 
 2020  January   2000          
 2020  November  6000          
 2020  December  2000          

See running example at DB Fiddle .请参阅DB Fiddle上的运行示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM