Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJonatan Spahn
6,362 PointsAverage of each movie
The third practice problem in the SQL playground asks you to calculate the average rating for each movie and round it.
I see that the following code has been posted from another asking a question about this. The code was as follows: SELECT ROUND(AVG(rating,1) AS average_rating FROM reviews
How would you get the AVG for EACH movie though? I tried starting simple with the following: SELECT DISTINCT movie_id FROM reviews; which return each movie_id which were 6,2, and 3, then I tried: SELECT DISTINCT movie_id, AVG(rating) FROM reviews; but that brought it up to two columns one with the count of distinct movie_id's which is 3 and one column with the average rating.
but how do you keep each distinct id and average each rating for each movie.
Thank you for any help you can offer!
3 Answers
Jay Meyer
7,708 PointsHey Jonatan, I'm not 100% sure I know what your asking, but I used:
SELECT movie_id, ROUND(AVG(rating),1) AS average_rating FROM reviews GROUP BY movie_id;
This brings up each movies ID and their corresponding AVG review. So it lists rows for id's 2, 3, and 6 and the average rating for each of those ID's. Hope this is what you were struggling with.
Dennis Amiel Domingo
17,751 PointsThe above answers are correct!
Though I went further since I wasn't satisfied with just looking at the ID's of the movies. I wanted to see the names of the movie beside the ratings.
So this is what I did.
SELECT title, movie_id, ROUND(AVG(rating),1) AS average_rating
FROM reviews, movies
WHERE reviews.movie_id = movies.id
GROUP BY movie_id;
You can also remove the movie_id in SELECT if you like.
Ethan Martin
Courses Plus Student 1,883 PointsHow does the code know which columns apply to each table? It doesn't appear the order of the tables after FROM matters or even the order in the WHERE clause.
Dennis Amiel Domingo
17,751 PointsEthan Martin, you need to include the name of the table to the column name, like this:
SELECT <table 1>.<column name>, <table 2>.<column name> FROM <table 1>, <table 2>;
SELECT reviews.title, movies.title FROM reviews, movies;
Antonio De Rose
20,885 PointsAntonio De Rose
20,885 Points