在網上查閱了很多方法,我嘗試了用後臺java,但實現起來比較麻煩,最後自己探索用純sql來實現,記錄起來分享下。
mysql 按月分組累計統計數據,想得到如下的結果,如下圖:
【year_and_month】- 顯示按月分組查詢的字段
【count_per_month】- 顯示每月分組統計的數量
【total_by_mont】- 顯示按月分組累計總數 = 本月分組統計數量 + 本月前所有月份分組統計數量
我的解決思路:
1、首先要準備或得到一個如下圖結果的表 "test_table" :
2、執行一下sql
SELECT
year_and_moth,
count_per_month,
(
SELECT
SUM(count_per_month)
FROM
test_table AS test_table_1
WHERE
test_table_1.year_and_moth <= test_table_2.year_and_moth
) AS total_by_month
FROM
test_table AS test_table_2
3、得出如下結果:
4、The end.