less than 1 minute read

Problem

problem-1204

Query

SELECT
    t.person_name
FROM
    (
        SELECT
            *,
            (@cumtotal := @cumtotal + q.weight) as total_weight
        FROM
            Queue as q,
            (SELECT @cumtotal:= 0 as cumtotal) temp
        ORDER BY
            turn
    ) t
WHERE
    t.total_weight <= 1000
ORDER BY
    t.total_weight DESC
LIMIT 1

Use Window Function Approach

SELECT
    q.person_name
FROM
    (
        SELECT
            *,
            SUM(weight) OVER (ORDER BY turn ASC) AS cumulative_sum
        FROM
            Queue
    ) q
WHERE
    q.cumulative_sum <= 1000
ORDER BY
    q.cumulative_sum DESC
LIMIT 1

Tags:

Updated: