title: Running total with in each group using MySQL
body: <p>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 using analytic functions but not in MySQL. Could you share your thoughts on how to implement it.</p>
  
  <p>SQL Fiddle :
  <a href="http://sqlfiddle.com/#!9/59366d/19" rel="nofollow noreferrer">http://sqlfiddle.com/#!9/59366d/19</a></p>
  
  <p>SQL using window function :</p>
  
  <pre><code>SELECT e.Id,
         SUM( e.Salary ) OVER( PARTITION BY e.Id ORDER BY e.Month  ) AS cumm_sal
    FROM Employee e 
  LEFT JOIN
         (
            SELECT Id,MAX(Month) AS maxmonth
              FROM Employee
            GROUP BY Id
          ) emax
      ON e.Id = emax.Id
  WHERE e.Month != emax.maxmonth
  ORDER BY e.Id,e.Month DESC;    
  </code></pre>
  
  <p>Input :</p>
  
  <pre><code>Create table Employee (Id int, Month int, Salary int);
  
  insert into Employee (Id, Month, Salary) values ('1', '1', '20');
  insert into Employee (Id, Month, Salary) values ('2', '1', '20');
  insert into Employee (Id, Month, Salary) values ('1', '2', '30');
  insert into Employee (Id, Month, Salary) values ('2', '2', '30');
  insert into Employee (Id, Month, Salary) values ('3', '2', '40');
  insert into Employee (Id, Month, Salary) values ('1', '3', '40');
  insert into Employee (Id, Month, Salary) values ('3', '3', '60');
  insert into Employee (Id, Month, Salary) values ('1', '4', '60');
  insert into Employee (Id, Month, Salary) values ('3', '4', '70');
  </code></pre>
  
  <p>Output :</p>
  
  <pre><code>| Id | Month | Salary |
  |----|-------|--------|
  | 1  | 3     | 90     |
  | 1  | 2     | 50     |
  | 1  | 1     | 20     |
  | 2  | 1     | 20     |
  | 3  | 3     | 100    |
  | 3  | 2     | 40     |
  </code></pre>