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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With