DatabaseProgramming: FindAlternativeFlights.sql

File FindAlternativeFlights.sql, 2.2 KB (added by 231044, 6 days ago)
Line 
1create or replace function FindAlternativeFlights(
2 CancelledFlightID int,
3 MaxHours int
4) returns table (
5 FlightID int,
6 FlightNumber varchar(6),
7 Departure timestamp,
8 Arrival timestamp,
9 HoursFromOriginal numeric,
10 SeatClass text,
11 AvailableSeats bigint
12) as $$
13declare
14 Origin_V char(3);
15 Destination_V char(3);
16 Departure_V timestamp;
17begin
18 select dap.code, aap.code, f.departure
19 into Origin_V, Destination_V, Departure_V
20 from flight f
21 join gate dg on dg.id = f.actualgatedepartureid
22 join terminal dt on dt.id = dg.terminalid
23 join airport dap on dap.id = dt.airportid
24 join gate ag on ag.id = f.actualgatearrivalid
25 join terminal at_ on at_.id = ag.terminalid
26 join airport aap on aap.id = at_.airportid
27 where f.id = CancelledFlightID;
28
29 if not FOUND then
30 raise exception 'Flight not found!';
31 end if;
32
33 return query
34 select flight.id, flight.flightnumber, flight.departure, flight.arrival,
35 round(extract(epoch from (flight.departure - Departure_V)) / 3600.0, 2),
36 seatclass.name::text, count(*) filter (where seat.reserved = false)
37 from flight
38 join gate dg on dg.id = flight.actualgatedepartureid
39 join terminal dt on dt.id = dg.terminalid
40 join airport dap on dap.id = dt.airportid
41 join gate ag on ag.id = flight.actualgatearrivalid
42 join terminal at_ on at_.id = ag.terminalid
43 join airport aap on aap.id = at_.airportid
44 join seat on seat.flightid = flight.id
45 join seatconfiguration on seatconfiguration.id = seat.seatconfigurationid
46 join seatclass on seatclass.id = seatconfiguration.seatclassid
47 where flight.id <> CancelledFlightID
48 and dap.code = Origin_V
49 and aap.code = Destination_V
50 and flight.departure between Departure_V - make_interval(hours => MaxHours)
51 and Departure_V + make_interval(hours => MaxHours)
52 and not exists (select 1 from canceledflight where public.canceledflight.flightid = flight.id)
53 group by flight.id, flight.flightnumber, flight.departure, flight.arrival, seatclass.name
54 having count(*) filter (where seat.reserved = false) > 0
55 order by flight.departure, seatclass.name;
56end;
57$$ language plpgsql;
58
59