10SQL window functions (SQLite)
10 SQL window functions (SQLite)
One Netflix data scientist reported a first round of "pure SQL, had to actually run" (1 report), and a prep site
lists an Airbnb screen question on a user-day panel over an inclusive date range (1 source). This is practice in
that shape: four queries against a table bookings(booking_id, guest_id, listing_id, city, booked_on, nights, price), with booked_on an ISO date string ('2026-01-04').
Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/10_sql_windows -k level1. Earlier levels must keep passing. Fill in the queries in
solution.py.
Level 1. TOP_LISTINGS_BY_CITY: per city, the 2 listings with the most revenue (price * nights, summed),
ties broken by the lower listing_id. Columns city, listing_id, revenue, rank, ordered by city then rank.
Level 2. DAYS_TO_SECOND_BOOKING: per guest, whole days from their first booking to their second (by
booked_on, ties by booking_id), as an integer, NULL for guests with one booking. A guest's second booking is
their second row, so two bookings on the same day give 0. Columns guest_id, days, ordered by guest.
Level 3. ROLLING_7D: per city, for every date that has bookings, how many bookings that city had in the 7
days ending on that date (that date and the 6 before it). One row per city and date. Columns city, booked_on, bookings_7d, ordered by city then date.
Level 4. GUEST_DAY_PANEL: every guest on every day from the table's first booking date to its last, both
included, with that guest's bookings that day, 0 when there were none. Every guest gets the same full range, not
just the days between their own bookings. day is an ISO date string like booked_on. Columns guest_id, day, bookings, ordered by guest then day.
Things to get right: ROW_NUMBER versus RANK versus DENSE_RANK on ties, LEAD and LAG, ordering by the date and not
the id, RANGE (by date) versus ROWS (by row) in a window frame, and the calendar and LEFT JOIN that give the empty
days rows of their own. In SQLite, date arithmetic goes through julianday().