Skip to content Skip to sidebar Skip to footer

Running Total With In Each Group Using Mysql

I am trying to write a SQL to calculate running total with in each group in the below input. Just wondering how can I do it using MySQL. I am aware of how to do it in regular SQL u

Solution 1:

In MySQL, the most efficient approach is to use variables:

selecte.*,
       (@s := if(@id = e.id, @s + salary,
                 if(@id := e.id, salary, salary)
                )
       ) asrunning_salaryfrom (select e.*
      from employee e
      order by e.id, e.month
     ) ecrossjoin
     (select @id := -1, @s := 0) params;

You can also do this with a correlated subquery:

select e.*,
       (selectsum(e2.salary)
        from employee e2
        where e2.id = e.id and e2.month <= e.month
       ) as running_salary
from employee e;

Post a Comment for "Running Total With In Each Group Using Mysql"