Window Functions · Problem 80 of 118

Rating Drops

HardWindow FunctionsShop data

Order the reviews of product 11 by review_date, then review_id. Return review_id, rating and previous_rating for every review whose rating is lower than the previous review's rating (the first review has no previous one and is not returned). Sort by review_date, then review_id.

Hint 1

Compute LAG(rating) in a CTE, then filter in the outer query.

Reference solution

WITH ordered AS (
  SELECT review_id, review_date, rating,
         LAG(rating) OVER (ORDER BY review_date, review_id) AS previous_rating
  FROM reviews
  WHERE product_id = 11
)
SELECT review_id, rating, previous_rating
FROM ordered
WHERE rating < previous_rating
ORDER BY review_date, review_id;

Window functions run after WHERE. If you remove rows in the same query's WHERE, "the previous row" becomes the previous remaining row, which changes the answer. Compute the window over the complete set of rows you need, in one step, then filter on the result in the next step. This ordering of steps (window first, then filter) is why top-N and "compare with previous" queries need a CTE or subquery.