Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum until certain point - MySql

Tags:

mysql

sum

How to do query and display the records until it reaches a certain number?

Suppose you want to select student until the total sum of the student's money reaches 1000?

Addition

 Student ID   Student Name   Student Money 
 ---------    -----------     --------------
   1           John            190
   2           Jenny           290
   3           Ben             200
   4           Andy            120
   5           Lynna           300

If I wanna stop at 500, I would get record number 1 and 2 (190 + 290). If I wanna stop at 1000, I would get record 1 until 4.

like image 347
henry Avatar asked May 08 '09 13:05

henry


1 Answers

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;
like image 198
sreimer Avatar answered Sep 22 '22 12:09

sreimer