Coding Test

1204. Last Person to Fit in the Bus

Indo Yoon

Last Person to Fit in the Bus - LeetCode
Can you solve this real interview question? Last Person to Fit in the Bus - Table: Queue +-------------+---------+| Column Name | Type |+-------------+---------+| person_id | int || person_name | varchar || weight | int || turn | int |+-------------+---------+p…

It's a simple problem to calculate cumulative sum. But the question is how to do so in SQL?

The first idea I've came up with was using AGG() OVER , and I tried OVER(PARTITION BY turn) which was wrong. When I usedOVER(ORDER BY turn) , this gives me the correct result.

The whole code is below:

SELECT person_name
FROM (
  SELECT person_name, turn, SUM(weight) OVER (ORDER BY turn) AS cum
  FROM Queue
) AS Temp
WHERE CUM <= 1000
ORDER BY cum DESC
LIMIT 1

Then why was it correct? I asked this to ChatGPT:


The SUM() OVER() construct in SQL gives a cumulative sum because of the way the OVER clause works.

When you use SUM() OVER (ORDER BY column), it calculates the sum in the order specified by the column, and for each row, it includes all rows up to and including that row in the sum. This is why it gives a cumulative sum.

Here’s a simple example:

Suppose you have a table sales:

sale_idsale_amount
1100
2200
3300

If you run the query SELECT sale_id, sale_amount, SUM(sale_amount) OVER (ORDER BY sale_id) as cumulative_sum FROM sales;, you would get:

sale_idsale_amountcumulative_sum
1100100
2200300
3300600

As you can see, for each row, the cumulative_sum column contains the sum of sale_amount for that row and all preceding rows, in the order of sale_id. This is why SUM() OVER (ORDER BY column) gives a cumulative sum.


In summary, OVER window function can count on preceding rows and a current row. Simple, but powerful!