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