You are given two tables: Buses and Passengers.
The Buses table contains information about bus arrivals at the LeetCode station:
bus_id(int): Unique identifier for each busarrival_time(int): Time when the bus arrives at the station
The Passengers table contains information about passenger arrivals:
passenger_id(int): Unique identifier for each passengerarrival_time(int): Time when the passenger arrives at the station
Passenger Assignment Rules:
- A passenger will board a bus if the passenger's arrival time is less than or equal to the bus's arrival time
- Each passenger boards the first available bus (earliest bus they are eligible for)
- Once a passenger boards a bus, they cannot board another bus
Write an SQL query to find the number of passengers that board each bus. Return the result ordered by bus_id in ascending order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
bus_id
PK
|
int | Unique identifier for each bus |
arrival_time
|
int | Time when the bus arrives at the station |
| Column Name | Type | Description |
|---|---|---|
passenger_id
PK
|
int | Unique identifier for each passenger |
arrival_time
|
int | Time when the passenger arrives at the station |
Input & Output
| bus_id | arrival_time |
|---|---|
| 101 | 3 |
| 102 | 7 |
| passenger_id | arrival_time |
|---|---|
| 11 | 1 |
| 12 | 5 |
| 13 | 6 |
| bus_id | passengers_cnt |
|---|---|
| 101 | 1 |
| 102 | 2 |
Passenger 11 arrives at time 1 and can board Bus 101 (time 3) or Bus 102 (time 7), but takes the first available (Bus 101). Passengers 12 and 13 arrive at times 5 and 6 respectively, and both board Bus 102 (time 7) as it's their first eligible bus.
| bus_id | arrival_time |
|---|---|
| 201 | 2 |
| 202 | 8 |
| passenger_id | arrival_time |
|---|---|
| 21 | 4 |
| bus_id | passengers_cnt |
|---|---|
| 201 | 0 |
| 202 | 1 |
Passenger 21 arrives at time 4, which is after Bus 201 (time 2), so they cannot board it. They board Bus 202 (time 8) instead. Bus 201 has 0 passengers.
| bus_id | arrival_time |
|---|---|
| 301 | 10 |
| passenger_id | arrival_time |
|---|---|
| 31 | 2 |
| 32 | 4 |
| 33 | 7 |
| bus_id | passengers_cnt |
|---|---|
| 301 | 3 |
All three passengers arrive before Bus 301 (time 10), so all three passengers board this single bus.
Constraints
-
1 ≤ bus_id ≤ 1000 -
1 ≤ passenger_id ≤ 1000 -
1 ≤ arrival_time ≤ 1000 - No two buses arrive at the same time
- Each passenger boards at most one bus