Table: rental
col_name | col_type --------------+-------------------------- rental_id | integer rental_ts | timestamp with time zone inventory_id | integer customer_id | smallint return_ts | timestamp with time zone staff_id | smallint
Question 69
Instructions:
Definition
Hint
Table: rental
col_name | col_type --------------+-------------------------- rental_id | integer rental_ts | timestamp with time zone inventory_id | integer customer_id | smallint return_ts | timestamp with time zone staff_id | smallint
Sample results
count ------- 123 (1 row)
Solution
postgresWITH customer_rental_date AS (
SELECT
customer_id,
DATE(rental_ts) AS rental_date
FROM rental
WHERE DATE(rental_ts) >= '2020-05-24'
AND DATE(rental_ts) <= '2020-05-31'
GROUP BY
customer_id,
DATE(rental_ts)
),
customer_rental_date_diff AS (
SELECT
customer_id,
rental_date AS current_rental_date,
LAG( rental_date, 1) OVER(PARTITION BY customer_id ORDER BY rental_date) AS prev_rental_date
FROM customer_rental_date
)
SELECT COUNT(*) FROM (
SELECT
customer_id,
MIN(current_rental_date - prev_rental_date)
FROM customer_rental_date_diff
GROUP BY customer_id
HAVING MIN(current_rental_date - prev_rental_date) = 1
) X
;
Explanation
This query retrieves the count of customers who rented a movie within a consecutive day period during the last week of May 2020.
The query does this by first creating a common table expression (CTE) called customer_rental_date. This CTE filters the rental table to only include rentals that occurred between May 24th and May 31st, 2020. It then groups the rentals by customer and rental date.
The second CTE called customer_rental_date_diff calculates the time difference between the current rental date and the previous rental date for each customer.
The final SELECT statement selects the count of customers who have rented movies on consecutive days. It does this by first selecting the customer ID and the minimum time difference between the current rental date and the previous rental date for each customer. It then groups the results by customer ID and filters the results to only include customers whose minimum time difference is equal to 1 day.
Last Submission
postgresNo submission yet for this engine. Run and submit your query to save it here.
Submit a query to compare against expected output.
Interview timer
Recommended interview pacing
Easy: 5 min for direct warm-up style questions.
Medium: 10 min for multi-step interview queries.
Hard: 15 min for layered questions with tighter time pressure.
A common bar is solving about 2 medium-or-harder questions in a 30 minute interview.
15:00
Run your query to preview results here.