I am trying to calculate the cumulative profit from all clients and I find a very good reference from here. However, my table consist of more than 1 client that should have their own cumulative profit. Below is the table 'client' that I already have.
| Year | Month | id | profit | cumulative |
| 2017 | 1 | 123 | 1000 | |
| 2017 | 2 | 123 | -200 | |
| 2017 | 3 | 123 | 500 | |
| 2017 | 1 | 456 | 500 | |
| 2017 | 2 | 456 | 100 | |
| 2017 | 3 | 456 | 200 | |
If I am using a sql code like this:
SET @csum := 0;
UPDATE client
SET cumulative = (@csum := @csum + profit);
The result I get is like this:
| Year | Month | id | profit | cumulative |
| 2017 | 1 | 123 | 1000 | 1000 |
| 2017 | 2 | 123 | -200 | 800 |
| 2017 | 3 | 123 | 500 | 1300 |
| 2017 | 1 | 456 | 500 | 1800 |
| 2017 | 2 | 456 | 100 | 1900 |
| 2017 | 3 | 456 | 200 | 2100 |
What I expect to get is like this:
| Year | Month | id | profit | cumulative |
| 2017 | 1 | 123 | 1000 | 1000 |
| 2017 | 2 | 123 | -200 | 800 |
| 2017 | 3 | 123 | 500 | 1300 |
| 2017 | 1 | 456 | 500 | 500 |
| 2017 | 2 | 456 | 100 | 600 |
| 2017 | 3 | 456 | 200 | 800 |
I am trying to group it by Year, Month, and id as well, but it doesn't work. Basically, I want the cumulative sum for every unique client in each month. Do you have any idea how to solve this? Thanks in advance.