Aggregation and Grouping · Problem 39 of 118

Well-Reviewed Products

HardAggregation and GroupingShop data

Return product_id, reviews (number of reviews) and average_rating (rounded to 2 decimals) for products with at least 10 reviews. Show the five best average ratings; sort by average_rating from high to low, then product_id.

Hint 1

Two conditions on the group: a minimum count (HAVING) and the top five (LIMIT).

Reference solution

SELECT product_id,
       COUNT(*) AS reviews,
       ROUND(AVG(rating), 2) AS average_rating
FROM reviews
GROUP BY product_id
HAVING COUNT(*) >= 10
ORDER BY average_rating DESC, product_id
LIMIT 5;

An average over two reviews is not trustworthy, so rankings of averages need a minimum sample size. HAVING COUNT(*) >= 10 removes the thin groups before the ranking. Without it, a product with a single 5-star review beats a product with 200 reviews averaging 4.9. Spotting small-sample noise is part of being a good analyst.