在MySQL中,最有效的方法是使用变量:
select e.*, (@s := if(@id = e.id, @s + salary, if(@id := e.id, salary, salary) ) ) as running_salaryfrom (select e.* from employee e order by e.id, e.month ) e cross join (select @id := -1, @s := 0) params;
您也可以使用相关子查询来执行此操作:
select e.*, (select sum(e2.salary) from employee e2 where e2.id = e.id and e2.month <= e.month ) as running_salaryfrom employee e;



