Sum until certain point - MySql

Came across this question while searching for my own answer. I thought I'd leave my solution here since it's another way to accomplish the same task and may be more efficient. The trick is the self join using >=

    SELECT s1.ID, s1.name, s1.money, sum(s2.money) as accumulator
    FROM student s1 
    INNER JOIN student s2 ON s1.id >= s2.id 
    GROUP BY s1.id HAVING accumulator <= 500;

There is no "intrinsic" order to a SQL table, so you'll have to specify some ORDER BY clause to give that "until" phrase any meaning. Given that, the sum of the ``first'' N records can be obtained with a SELECT SUM(money) FROM student ORDER BY xxx LIMIT N. Using an auxiliary table INTS which has integers in natural order, you can find the maximum suitable N by something like:

SELECT MAX(N) FROM INTS
WHERE (SELECT SUM(money) FROM student ORDER BY xxx LIMIT N) < 1000

and finally insert this as another nested SELECT for the LIMIT clause in your overall SELECT. All of this smells like it would be rather inefficient, though! As often when nested SELECTs seem too many and too slow, an alternative is doing this in steps: first build a temporary table with the "progressive sums", then use that to help you find the limit you need.

Tags:

Mysql

Sum