Rating Trends Across a Rider's First and Third Months by City
SQL & DataModel answerLast updated
Write a PostgreSQL query returning, per city, the mean per-ride rating in each rider's first and third months with rides, handling skipped months, unrated rides and weighting.
A ride-hailing team wants to see whether riders score their trips differently as they stay with the product. For each city, compare the typical rating given during a rider's first month of use with the rating given during their third month of use.
Definitions
A rider's active months are the calendar months (year and month together) in which they took at least one ride. Number them in time order: the earliest is the rider's 1st active month, the next is the 2nd, and so on. Months with no rides are skipped, so the 3rd active month may be much later than two calendar months after the 1st.
Tables
users
| Column | Type | Notes |
|---|---|---|
user_id | INTEGER | Primary key |
city | TEXT | Never NULL |
rides
| Column | Type | Notes |
|---|---|---|
ride_id | INTEGER | Primary key |
ride_date | DATE | Never NULL |
ride_rating | INTEGER | 1 to 5, or NULL if the rider did not rate |
user_id | INTEGER | Always references users.user_id |
Task
Write a single read-only PostgreSQL query (one SELECT, CTEs allowed) that returns one row per city having at least one ride:
city(TEXT)month_1_avg_rating(NUMERIC): meanride_ratingacross all rides that fall in their rider's 1st active month, for riders in that city, rounded to 2 decimals.month_3_avg_rating(NUMERIC): the same for the 3rd active month, rounded to 2 decimals; NULL when the city has no rated ride in that position.
Sort by city ascending.
Rules
- Average over individual rides, not over per-user averages. A rider with three rides in the month supplies three values.
- Every ride, rated or not, counts when deciding which months are active. Unrated rides are excluded only from the averages.
- Months are identified by year and month, so January 2024 and January 2025 are different months.
- Riders with fewer than three active months still count toward the month-1 column.
- If every month-1 ride in a city is unrated,
month_1_avg_ratingis NULL (the city still appears). - Riders with no rides have no effect; a city with no rides is absent.
Example
users
| user_id | city |
|---|---|
| 1 | SF |
| 2 | SF |
| 3 | LA |
rides
| ride_id | ride_date | ride_rating | user_id |
|---|---|---|---|
| 1 | 2024-01-05 | 5 | 1 |
| 2 | 2024-01-20 | 5 | 1 |
| 3 | 2024-01-31 | 2 | 1 |
| 4 | 2024-02-10 | 4 | 1 |
| 5 | 2024-04-02 | 2 | 1 |
| 6 | 2024-04-18 | NULL | 1 |
| 7 | 2024-02-03 | 2 | 2 |
| 8 | 2024-03-09 | NULL | 2 |
| 9 | 2024-05-01 | 3 | 2 |
| 10 | 2024-03-15 | 5 | 3 |
| 11 | 2024-03-28 | 4 | 3 |
Expected output:
| city | month_1_avg_rating | month_3_avg_rating |
|---|---|---|
| LA | 4.50 | NULL |
| SF | 3.50 | 2.50 |
Rider 1's active months are Jan, Feb, Apr; rider 2's are Feb, Mar (one unrated ride, still active), May; rider 3 has only Mar. SF month 1 is (5+5+2+2)/4 = 3.50, whereas averaging the two riders' own averages would wrongly give 3.00.
What to deliver
Provide the query and explain how you number the months, why that choice is correct, and how NULL ratings and the weighting rule are handled.
Hints
Hint 1
Work in two phases: first label each ride with the number of its rider's active month, then aggregate ratings by city and that number.
Hint 2
Number months, not rides. Truncate ride_date to the month (keeping the year) and use a ranking function that gives equal values the same rank and leaves no gaps; compare ROW_NUMBER, RANK and DENSE_RANK.
Hint 3
Do not filter out NULL ratings before ranking, because an unrated ride still makes its month active. Let AVG skip NULLs, and use FILTER (or CASE) to get both columns in one GROUP BY.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task splits cleanly into two steps, and most errors come from mixing them up.
- Label each ride with its rider's active-month number. Truncate
ride_dateto the month, then rank each user's distinct months in time order. This step must see all rides, including unrated ones, because an unrated ride still makes its month active. - Aggregate by city and month number. Average
ride_ratingover individual rides, separately for month number 1 and 3.AVGignores NULLs, so unrated rides drop out here and not earlier.
Numbering the months
date_trunc('month', ride_date) maps every date to the first day of its month and preserves the year, so Jan 2024 and Jan 2025 stay distinct. EXTRACT(MONTH ...) would merge them and is a bug.
Two correct ways to rank:
SELECT DISTINCT user_id, month, applyROW_NUMBER() OVER (PARTITION BY user_id ORDER BY month), then join back to rides.- Apply
DENSE_RANK() OVER (PARTITION BY user_id ORDER BY date_trunc('month', ride_date))straight on the ride rows. Rides in the same month tie and share a rank, and there are no gaps, so the third distinct month gets rank 3.
ROW_NUMBER over rides is wrong (three January rides would become ranks 1, 2, 3). RANK is also wrong because it leaves gaps: after three tied January rides, February would be rank 4.
Aggregation
Use filtered aggregates so both columns come from one pass:
ROUND(AVG(ride_rating) FILTER (WHERE month_rank = 1), 2)
ROUND(AVG(ride_rating) FILTER (WHERE month_rank = 3), 2)
In PostgreSQL, AVG over an INTEGER returns NUMERIC, so ROUND(x, 2) works and matches the required output type. If the filtered set is empty or contains only NULLs, AVG returns NULL, which is exactly the required behavior. AVG(CASE WHEN month_rank = 3 THEN ride_rating END) is an equivalent, more portable form.
Solution
WITH ranked_rides AS (
SELECT
u.city,
r.ride_rating,
DENSE_RANK() OVER (
PARTITION BY r.user_id
ORDER BY date_trunc('month', r.ride_date)
) AS month_rank
FROM rides AS r
JOIN users AS u
ON u.user_id = r.user_id
)
SELECT
city,
ROUND(AVG(ride_rating) FILTER (WHERE month_rank = 1), 2) AS month_1_avg_rating,
ROUND(AVG(ride_rating) FILTER (WHERE month_rank = 3), 2) AS month_3_avg_rating
FROM ranked_rides
GROUP BY city
ORDER BY city;
Why it is correct
- Ranking sees every ride. The window function runs before any rating filter, so a month with only unrated rides still occupies a rank. In the example, rider 2's March is rank 2, which makes May rank 3.
- Ranks follow distinct months, not calendar distance. Rider 1's April is rank 3 even though it is two months after February.
- Averages are per ride. Each row contributes once, so SF month 1 is (5+5+2+2)/4 = 3.50, not the 3.00 you get by averaging per-user means.
- City set is right. The inner join starts from rides, so riders without rides and cities without rides never appear. Any rider with a ride has a rank-1 month, so every city with a ride gets a row.
- NULLs behave as specified. SF month 3 sees {2, NULL, 3};
AVGignores the NULL and returns 2.50. LA has no rank-3 rows, so its month-3 value is NULL.
Complexity
With R rides:
- Time: O(R log R), dominated by sorting or partitioning for the window; the join and group-by are linear or hash-based.
- Space: O(R) for window buffers, plus O(cities) for aggregate state.
An index on rides(user_id, ride_date) can let the planner feed the window without a full sort.
Edge cases
- Same month in different years: handled by keeping the year in the truncation.
- A month with only unrated rides: it counts as active but adds nothing to the averages.
- Rider with fewer than three active months: contributes to month 1 only.
- A city whose month-1 rides are all unrated:
month_1_avg_ratingis NULL, and the row is still returned. - Gaps between active months: never compute "first ride plus two months"; the definition is by rank.
- Month boundaries such as Jan 31 and Feb 1: truncation places them correctly, while day-difference arithmetic would not.
Common mistakes
- Using
ROW_NUMBER()orRANK()over rides instead ofDENSE_RANK()(orROW_NUMBER()over distinct months). - Adding
WHERE ride_rating IS NOT NULLbefore ranking, which deletes active months and shifts later ranks. - Averaging per-user monthly averages instead of per-ride values.
- Running separate month-1 and month-3 queries and combining them with an inner join, which drops cities lacking month-3 data. If you split the query, start from the month-1 result with a
LEFT JOIN. - Omitting
ROUND(..., 2)or the finalORDER BY city.
A strong answer states the two-phase structure first, explains why ranking must include unrated rides, and justifies the choice of DENSE_RANK over RANK and ROW_NUMBER without being prompted.