SQL
Lab
Uber Uber Interview Question 09

Driver
Retention

Find drivers who completed trips in both January and February.

Table Schema

Inspect
Table

interactive
ColumnType
driver_idinteger
trip_datedate

Sample Data

Input
Output

Sample Input: trips
driver_idtrip_date
2012024-01-01
2012024-02-01
2022024-01-05
2032024-02-10
2042024-01-15
2042024-02-20
Expected Output
driver_id
201
204

SQL Editor

Run
Query

postgresql
Waiting for query

driver_id
201
204

Hints

Unlock
Clues

Hint 01: Identify the grouping level required by the output.
Hint 02: Aggregate with COUNT, SUM, AVG, or a window function as needed.
Hint 03: Filter after aggregation with HAVING or after ranking with an outer query.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

SELECT driver_id
FROM trips
WHERE trip_date >= DATE '2024-01-01'
  AND trip_date < DATE '2024-03-01'
GROUP BY driver_id
HAVING COUNT(DISTINCT DATE_TRUNC('month', trip_date)) = 2;

Explanation

Step By
Step

01

Read the expected output columns to determine the final grain.

02

Aggregate or rank the input rows to calculate the requested metric.

03

Filter, sort, and alias the final columns to match the output.

Related Questions

Keep
Solving