SQL
Lab
Uber Uber Interview Question 08

Trip
Distance
Bucketing

Categorize trips into short (<5km), medium (5-15km), long (>15km) and count them.

Table Schema

Inspect
Table

interactive
ColumnType
trip_idinteger
distance_kmdecimal

Sample Data

Input
Output

Sample Input: trips
trip_iddistance_km
12
26
312
420
54
615
718
Expected Output
categorytrip_count
short2
medium3
long2

SQL Editor

Run
Query

postgresql
Waiting for query

categorytrip_count
short2
medium3
long2

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
  CASE
    WHEN distance_km < 5 THEN 'short'
    WHEN distance_km <= 15 THEN 'medium'
    ELSE 'long'
  END AS category,
  COUNT(*) AS trip_count
FROM trips
GROUP BY category;

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