Skip to content
Advertisement

How to calculate running sum for each group in MySQL

Straightforward summation I can do with sum() function. But I’ve a different situation here. I’ve a table Student with only 2 fields. For instance just assume that there is only 1 student in the entire class:

And I have his scores for the days when exams were taken with one more column in the runtime which is the month in which exam was held:

The query is (took help from stackoverflow yesterday):

Result:

My requirement is I want to reward this student every month. I’ll keep on adding his score for each date for each individual month and give him Reward1 when accumulated score sum reaches 10 and Reward2 when accumulated score sum reaches 20. So the final table should like this:

Reward fields can be boolean and empty reward rows can be set to N or False or whatever seems logical. This was not helpful: Calculate running sum

Please help me achieve this objective. Suggest some approach.

Here is a fiddle.

Advertisement

Answer

First calculate the running sum of the scores for each month in a CTE.
Then apply your conditions:

See the demo.
Results:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement