SQL
Lab
Amazon Easy Date Average

Average
Review
Ratings

Retrieve the average star rating for each product, grouped by month.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
review_idintegerUnique review identifier.
user_idintegerUser who submitted the review.
submit_datedatetimeTimestamp when the review was submitted.
product_idintegerReviewed product identifier.
starsintegerStar rating from 1 to 5.

Sample Data

Input
Output

Sample Input: reviews
review_iduser_idsubmit_dateproduct_idstars
617112306/08/2022 00:00:00500014
780226506/10/2022 00:00:00698524
529336206/18/2022 00:00:00500013
635219207/26/2022 00:00:00698523
451798107/05/2022 00:00:00698522
Expected Output
mthproductavg_stars
6500013.50
6698524.00
7698522.50

SQL Editor

Run
Query

postgresql
Waiting for query

mthproductavg_stars
6500013.50
6698524.00
7698522.50

Hints

Unlock
Clues

Hint 01: Extract the month number from submit_date.
Hint 02: Group by the extracted month and product_id.
Hint 03: Use ROUND(AVG(stars), 2), then order by month and product.

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.

SELECT
  EXTRACT(MONTH FROM submit_date) AS mth,
  product_id AS product,
  ROUND(AVG(stars), 2) AS avg_stars
FROM reviews
GROUP BY
  EXTRACT(MONTH FROM submit_date),
  product_id
ORDER BY mth, product;

Explanation

Step By
Step

01

Extract the numeric month from submit_date so reviews can be grouped by month.

02

Group by that month and product_id, then average the stars for each group.

03

Round the average to two decimal places and sort by month, then product.

Related Questions

Keep
Solving