SQL
Lab
Uber Uber Interview Question 02

Surge
Pricing
Detection

Find time periods where average fare increased by more than 50% compared to the previous hour.

Table Schema

Inspect
Table

interactive
ColumnType
trip_idinteger
cityvarchar
faredecimal
request_timedatetime

Sample Data

Input
Output

Sample Input: trips
trip_idcityfarerequest_time
1NYC1009:00
2NYC1209:30
3NYC2510:00
4NYC3010:30
5NYC2011:00
6NYC2211:30
Expected Output
houravg_fare
10:0027.50

SQL Editor

Run
Query

postgresql
Waiting for query

houravg_fare
10:0027.50

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.

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

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