这不起作用,因为
GROUP
惯性导航与制导。你需要把
组
作为子查询,并根据该查询计算运行总数:
SELECT monthname as month, year, contracts, totals,
@running_total := @running_total + totals AS running_totals
FROM (SELECT
MONTHNAME(w.app_date) monthname,
MONTH(w.app_date) monthnum,
YEAR(w.app_date) year,
COUNT(*) contracts,
SUM(w.total_price) totals
FROM (SELECT
app_date,
SUM(price * term) total_price
FROM _loans l
GROUP BY l.loan_id
) w
GROUP BY year, monthnum, monthname
) t
JOIN (SELECT @running_total := 0) r
ORDER BY year, monthnum ASC
输出:
month year contracts totals running_totals
January 2019 6 63234.72 63234.71923828125
February 2019 10 85703.04 148937.75939941406
March 2019 4 46727.04 195664.79919433594
Demo on dbfiddle