https://popsql.com/learn-sql/mysql/how-to-calculate-cumulative-sum-running-total-in-mysql Use @ Select t0.person_name FROM (SELECT turn , person_id , person_name , weight , (@csum := @csum + weight) as cumulative_weight FROM Queue ,(SELECT @csum := 0) r order by turn) as t0 WHERE cumulative_weight <= 1000 ORDER BY cumulative_weight DESC LIMIT 1 Use Over with CTE as ( Select person_id, person_name, weight, turn, sum(weight) over (order by turn) as Total_weight from Queue ) Select person_name from CTE where total_weight<=1000 order by total_weight DESC limit 1 Use Math!! SELECT q1.person_name FROM Queue q1, Queue q2 WHERE q1.turn >= q2.turn GROUP BY q1.turn HAVING SUM (q2.weight) <= 1000 ORDER BY SUM (q2.weight) DESC LIMIT 1 Input: Queue table: +-----------+-------------+--------+------+ | person_id | person_name | weight | turn | +-----------+-------------+--------+------+ | 5 | Alice | 250 | 1 | | 4 | Bob | 175 ...