Window SUM for cumulative weight
WITH queue_weights AS (
SELECT
person_name,
turn,
SUM(weight) OVER (ORDER BY turn) AS cum_weight
FROM queue
)
SELECT
person_name
FROM queue_weights
WHERE cum_weight <= 1000
ORDER BY cum_weight DESC
LIMIT 1This is the standard solution. The window SUM builds the running weight by boarding order, and the final filter keeps only the feasible passengers before selecting the latest one.