简体   繁体   中英

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.

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). Zebra date picker gives the year.

In this scenario user select the year 2020 and it's should show the values as below.

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

you can use group by like this in your query

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

and then select like this

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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