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;

Leave a Comment