How to execute a request and display records until it reaches a certain number?
Suppose you want to choose a student until the total student 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 want to stay at 500, I would get the record number 1 and 2 (190 + 290). If I want to stop at 1000, I get a record of 1 to 4.
SQL- "" , - ORDER BY, "" . , "" N SELECT SUM (money) FROM student ORDER BY xxx LIMIT N. INTS, , N, :
SELECT MAX(N) FROM INTS WHERE (SELECT SUM(money) FROM student ORDER BY xxx LIMIT N) < 1000
, , SELECT LIMIT SELECT. , ! , SELECT , : " ", , .
. , , . - , >=
>=
SELECT s1.ID, s1.name, s1.money, sum(s2.money) FROM student s1 INNER JOIN student s2 ON s1.id >= s2.id GROUP BY s1.id HAVING SUM(s2.money) <= 500;
... MySQL... MS SQL...
, ROW_NUMBER().
SELECT Student.*, SUM(StudentBefore.Money) AS AccumulatedMoney FROM ( SELECT *, ROW_NUMBER() OVER(ORDER BY Id) AS RowNumber FROM Students ) AS Student INNER JOIN ( SELECT *, ROW_NUMBER() OVER(ORDER BY Id) AS RowNumber FROM Students ) AS StudentBefore ON StudentBefore.RowNumber <= Student.RowNumber GROUP BY Student.RowNumber, Student.Id, Student.Name, Student.Money HAVING SUM(StudentBefore.Money) < 1000
, . , , , , - .