Buses and passengers arrive at a station. If a bus arrives at the station at a time tbus
and a passenger arrives at a time tpassenger where tpassenger <= tbus,
then the passenger will attempt to use the first available bus whose capacity has not been exceeded.
If at the moment the bus arrives at the station there are more passengers waiting than its capacity capacity,
only capacity passengers will use the bus.
I want to output the users that appear on each bus (if two passengers arrive at the same time, then the passenger with the smaller passenger_id value should be given priority).
Input:
Buses table:
| bus_id | arrival_time | capacity |
|---|---|---|
| 1 | 2 | 1 |
| 2 | 4 | 10 |
| 3 | 7 | 2 |
Passengers table:
| passenger_id | arrival_time |
|---|---|
| 11 | 1 |
| 12 | 1 |
| 13 | 5 |
| 14 | 6 |
| 15 | 7 |
Output:
| bus_id | capacity | b_arrival | spot | passenger_id | p_arrival |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 1 | 11 | 1 |
| 2 | 10 | 4 | 1 | 12 | 1 |
| 2 | 10 | 4 | 2 | NULL | NULL |
| 2 | 10 | 4 | 3 | NULL | NULL |
| 2 | 10 | 4 | 4 | NULL | NULL |
| 2 | 10 | 4 | 5 | NULL | NULL |
| 2 | 10 | 4 | 6 | NULL | NULL |
| 2 | 10 | 4 | 7 | NULL | NULL |
| 2 | 10 | 4 | 8 | NULL | NULL |
| 2 | 10 | 4 | 9 | NULL | NULL |
| 2 | 10 | 4 | 10 | NULL | NULL |
| 3 | 2 | 7 | 1 | 13 | 5 |
| 3 | 2 | 7 | 2 | 14 | 6 |
Explanation:
Passenger 11 arrives at time 1.
Passenger 12 arrives at time 1.
Bus 1 arrives at time 2 and collects passenger 11 as it has one empty seat.
Bus 2 arrives at time 4 and collects passenger 12 as it has ten empty seats.
Passenger 13 arrives at time 5.
Passenger 14 arrives at time 6.
Passenger 15 arrives at time 7.
Bus 3 arrives at time 7 and collects passengers 13 and 14 as it has two empty seats.
DDL:
create table buses(id int, arrival_time int, capacity int)
insert into buses values(1,2,1),(2,4,10),(3,7,2)
create table passengers (passenger_id int, arrival_time int)
insert into passengers values(11,1),(12,1),(13,5),(14,6),(15,7)
