SQL Tutorial: Average Star Rating by Month and Product
Introduction
Structured Query Language (SQL) is a powerful tool for managing and analyzing relational data. In
this tutorial, we focus on how to compute the average star rating for each product, grouped by the
month of the review. This type of aggregation is common in reporting and business intelligence
applications.
Problem Statement
Given a table called 'reviews' with columns like review_date, product_id, and star_rating, write a
query to calculate the average star rating for each product, grouped by the month of the review date.
The result should display:
- Month (as a number)
- Product ID
- Average star rating (rounded to two decimal places)
The output should be sorted first by month and then by product ID.
SQL Query
SELECT
MONTH(review_date) AS month,
product_id,
ROUND(AVG(star_rating), 2) AS average_rating
FROM
reviews
GROUP BY
MONTH(review_date), product_id
ORDER BY
month, product_id;
SQL Tutorial: Average Star Rating by Month and Product
Step-by-Step Explanation
- MONTH(review_date): Extracts the numeric month (1-12) from each review date.
- product_id: Identifies the product being reviewed.
- AVG(star_rating): Computes the average rating for each group of (month, product).
- ROUND(..., 2): Rounds the average to two decimal places.
- GROUP BY: Groups data by month and product ID.
- ORDER BY: Sorts results by month first, then by product ID.
Example Input Data
| review_date | product_id | star_rating |
|-------------|------------|-------------|
| 2023-01-10 | 101 | 4 |
| 2023-01-15 | 101 | 5 |
| 2023-02-01 | 102 | 3 |
| 2023-01-20 | 103 | 2 |
| 2023-02-12 | 101 | 4 |
Expected Output
| month | product_id | average_rating |
|-------|------------|----------------|
| 1 | 101 | 4.50 |
| 1 | 103 | 2.00 |
| 2 | 101 | 4.00 |
| 2 | 102 | 3.00 |
Conclusion
This query is a practical example of how SQL can be used to generate meaningful analytics, such
as product performance trends over time. Understanding how to group data and apply aggregate
SQL Tutorial: Average Star Rating by Month and Product
functions is essential for any data professional.