ExpertJoins50 points

Out and back within a week: round-trip travellers

The ancillary sales team wants to target business travellers who fly out and come back within days. A round trip is a pair of completed flights taken by the same passenger where the second flight flies the exact reverse route of the first (for example LHR to JFK then JFK to LHR) and departs between 1 and 7 calendar days after the first one (compare the date parts of sched_dep, same-day returns do not count). Each different pair of bookings counts as one round trip.

Task: self-join bookings, flights and routes to find those pairs and return passenger (name), round_trips (number of pairs) and total_fare_usd (the sum of fare_usd of both bookings in every pair, a pair's two fares added together). Sort by round_trips from high to low, then total_fare_usd from high to low, then passenger A to Z.

The data you can query

Each table is shown with its column types and the first rows, so you can see exactly what the data looks like.

aircraft14 rows
id INTEGERairline TEXTmodel TEXTseats INTEGERdelivered_year INTEGER
1SkyMeridianA3201802017
2SkyMeridianA3201802019
3SkyMeridianA3212002021
4SkyMeridianB787-92902018
5SkyMeridianA350-9003202022
6SkyMeridianB787-92902020

Showing the first 6 of 14 rows.

airports12 rows
code TEXTname TEXTcity TEXTcountry TEXT
JFKJohn F. Kennedy InternationalNew YorkUSA
LHRHeathrowLondonUnited Kingdom
DXBDubai InternationalDubaiUAE
SINChangiSingaporeSingapore
LHEAllama Iqbal InternationalLahorePakistan
ISBIslamabad InternationalIslamabadPakistan

Showing the first 6 of 12 rows.

bookings557 rows
id INTEGERflight_id INTEGERpassenger_id INTEGERcabin TEXTfare_usd INTEGER
1114Economy230
2138Economy180
321Economy380
4222Economy400
5245Economy445
631Economy450

Showing the first 6 of 557 rows.

flights260 rows
id INTEGERflight_no TEXTroute_id INTEGERaircraft_id INTEGERsched_dep TEXTdep_delay_min INTEGERstatus TEXT
1FC1853122025-01-02 07:15:000Completed
2OW3708102025-01-03 05:30:0040Completed
3SM4893552025-01-03 08:00:0025Completed
4SM4153362025-01-03 14:45:0010Completed
5OW5921492025-01-08 16:00:0050Completed
6SM222422025-01-09 08:45:0035Completed

Showing the first 6 of 260 rows.

passengers45 rows
id INTEGERname TEXThome_country TEXTloyalty_tier TEXT
1Ayesha KhanPakistanSilver
2Bilal OkaforAustraliaSilver
3Chen SilvaGermanyNULL
4Diego TanakaAustraliaSilver
5Elena WeberGermanyNULL
6Farid NguyenAustraliaGold

Showing the first 6 of 45 rows.

routes40 rows
id INTEGERorigin TEXTdest TEXTdistance_km INTEGER
1LHEDXB2100
2DXBLHE2100
3ISBDXB2300
4DXBISB2300
5DXBLHR5500
6LHRDXB5500

Showing the first 6 of 40 rows.

Your query runs on SQLite. Write a single SELECT; use LIMIT instead of TOP.

Need a hint?

Join the same table twice with different aliases and let the date difference decide which side is the outbound flight.