Table Schema
Inspect
Table
| Column | Type |
|---|---|
| trip_id | integer |
| city | varchar |
| fare | decimal |
| request_time | datetime |
Find time periods where average fare increased by more than 50% compared to the previous hour.
Table Schema
| Column | Type |
|---|---|
| trip_id | integer |
| city | varchar |
| fare | decimal |
| request_time | datetime |
Sample Data
| trip_id | city | fare | request_time |
|---|---|---|---|
| 1 | NYC | 10 | 09:00 |
| 2 | NYC | 12 | 09:30 |
| 3 | NYC | 25 | 10:00 |
| 4 | NYC | 30 | 10:30 |
| 5 | NYC | 20 | 11:00 |
| 6 | NYC | 22 | 11:30 |
| hour | avg_fare |
|---|---|
| 10:00 | 27.50 |
SQL Editor
| hour | avg_fare |
|---|---|
| 10:00 | 27.50 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
WITH hourly AS (
SELECT DATE_TRUNC('hour', request_time) AS hour, AVG(fare) AS avg_fare
FROM trips
GROUP BY DATE_TRUNC('hour', request_time)
)
SELECT hour, avg_fare
FROM (
SELECT hour, avg_fare, LAG(avg_fare) OVER (ORDER BY hour) AS prev_avg_fare
FROM hourly
) h
WHERE avg_fare > prev_avg_fare * 1.5;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