Last active
August 29, 2015 14:01
-
-
Save arekrob/2d7166d0a11030419c55 to your computer and use it in GitHub Desktop.
MySQL Running Total
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
For example when I have table: | |
Id|Val | |
1 | 1 | |
2 | 2 | |
3 | 3 | |
4 | 4 | |
I'd like to get result like this: | |
Id|Val | |
1 | 1 | |
2 | 3 # 1+2 | |
3 | 6 # 1+2+3 | |
4 | 10 # 1+2+3+4 | |
You can do this by joining the table on itself. The SUM will add up all rows up to this row: | |
select cur.id, sum(prev.val) | |
from TheTable cur | |
left join TheTable prev | |
on cur.id >= prev.id | |
group by cur.id | |
MySQL also allows the use of user variables to calculate this, which is more efficient but considered something of a hack: | |
select | |
id | |
, @running_total := @running_total + val AS RunningTotal | |
from TheTable | |
--- | |
To get the first row where the sum of all the previous cash is greater than a certain value, use: | |
SELECT y.id, y.cash | |
FROM (SELECT t.id, | |
t.cash, | |
(SELECT SUM(x.cash) | |
FROM TABLE x | |
WHERE x.id <= t.id) AS running_total | |
FROM TABLE t | |
ORDER BY t.id) y | |
WHERE y.running_total > 500 | |
ORDER BY y.id | |
LIMIT 1 | |
Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment