Table Schema
Inspect
Table
| Column | Type |
|---|---|
| trip_id | integer |
| distance_km | decimal |
Categorize trips into short (<5km), medium (5-15km), long (>15km) and count them.
Table Schema
| Column | Type |
|---|---|
| trip_id | integer |
| distance_km | decimal |
Sample Data
| trip_id | distance_km |
|---|---|
| 1 | 2 |
| 2 | 6 |
| 3 | 12 |
| 4 | 20 |
| 5 | 4 |
| 6 | 15 |
| 7 | 18 |
| category | trip_count |
|---|---|
| short | 2 |
| medium | 3 |
| long | 2 |
SQL Editor
| category | trip_count |
|---|---|
| short | 2 |
| medium | 3 |
| long | 2 |
Hints
Solution
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
Read the expected output columns to determine the final grain.
Aggregate or rank the input rows to calculate the requested metric.
Filter, sort, and alias the final columns to match the output.
Related Questions