Leetcode Problem 2142. The Number of Passengers in Each Bus I

2142. The Number of Passengers in Each Bus I

Leetcode Solutions

Using Window Function LAG and LEFT JOIN

  1. Create a Common Table Expression (CTE) named cte that selects bus_id, arrival_time, and the arrival time of the previous bus using the LAG function.
  2. Set the default value of the LAG function to 0 to handle the first bus which has no previous bus.
  3. Perform a LEFT JOIN between the CTE cte and the Passengers table on the condition that the passenger's arrival time is greater than the previous bus's arrival time and less than or equal to the current bus's arrival time.
  4. Group the results by bus_id from the CTE.
  5. Count the number of passengers for each group to get the passengers_cnt.
  6. Order the final result by bus_id in ascending order.
erDiagram
    Buses {
        int bus_id PK
        int arrival_time
    }
    Passengers {
        int passenger_id PK
        int arrival_time
    }
    Buses ||--o{ Passengers : "has"

Using a Subquery to Determine the Minimum Bus Arrival Time for Each Passenger

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...