DatabaseCreation: PassengerLoyaltyProfile.sql

File PassengerLoyaltyProfile.sql, 1.5 KB (added by 231044, 7 days ago)
Line 
1create materialized view PassengerLoyaltyProgram (PassengerId, Name, Surname, DateOfBirth, Email,
2 MilePoints, TotalFlights, TotalSpent, MostFrequentOrigin, MostFrequentDestination) as
3with FlightAirports as (
4 select f.id as FlightID,
5 dAirport.code as OriginCode,
6 aAirport.code as DestinationCode
7 from flight f
8 join gate dg on dg.id = f.actualgatedepartureid
9 join terminal dt on dt.id = dg.terminalid
10 join airport dAirport on dAirport.id = dt.airportid
11 join gate ag on ag.id = f.actualgatearrivalid
12 join terminal at_ on at_.id = ag.terminalid
13 join airport aAirport on aAirport.id = at_.airportid
14),
15TicketSummary as (
16 select t.passengerid,
17 fa.OriginCode,
18 fa.DestinationCode,
19 t.finalprice
20 from ticket t
21 join FlightAirports fa on fa.FlightID = t.flightid
22),
23Aggregated as (
24 select passengerid,
25 count(*) as TotalFlights,
26 sum(finalprice) as TotalSpent,
27 mode() within group (order by OriginCode) as MostFrequentOrigin,
28 mode() within group (order by DestinationCode) as MostFrequentDestination
29 from TicketSummary
30 group by passengerid
31)
32select p.id, p.name, p.surname, p.dateofbirth,
33 p.email, p.milepoints,
34 coalesce(a.TotalFlights, 0),
35 coalesce(a.TotalSpent, 0),
36 a.MostFrequentOrigin,
37 a.MostFrequentDestination
38from passenger p
39left join Aggregated a on a.passengerid = p.id;
40
41