This short article answers the following PostgreSQL question:
The two tables that we are given have the following structure:
The first thing that we need to do is join both tables so we have all the necessary information in one table. We will do that with a Common Table Expression (CTE):
WITH temp AS(
SELECT
ta.train_id,
arrival_time,
departure_time
FROM train_arrivals ta
INNER JOIN train_departures td
ON ta.train_id = td.train_id
)
In order to find the minimum number of platforms needed, we have to calculate, for each train, how many trains are already in the station when said train arrives. For example, if train 5 arrives and there are 3 other trains already in the station (they arrived before and haven’t left yet), we would need a total of 4 platforms to accommodate all of the traffic.
We can accomplish that calculation by simply doing a self-join of the previous CTE. That way, for each train, we will calculate how many other trains coincide with it (in this context, coincide means that the time of the arriving train is between the arrival and departure time of any other trains). Since a train will always coincide with itself, we need to subtract one from that count:
WITH temp AS(
SELECT
ta.train_id,
arrival_time,
departure_time
FROM train_arrivals ta
INNER JOIN train_departures td
ON ta.train_id = td.train_id
)
SELECT
t1.train_id,
t1.arrival_time,
t1.departure_time,
(COUNT(t1.train_id) - 1) AS min_num_platforms
FROM temp t1
JOIN temp t2
ON t1.arrival_time BETWEEN t2.arrival_time AND t2.departure_time
GROUP BY 1, 2, 3
ORDER BY 4 DESC
That query will give us the following table:
As we can see, when train 4 arrives at the station, there would be 2 more trains already there (1 and 2), and train 5 would be arriving at the same time. Therefore, we would need at least 4 platforms to accommodate all scheduled traffic for the day. We can always calculate the minimum number of platforms needed for any given schedule by simply computing the maximum value of the min_number_platforms column.