I’m solving http://www.db-class.com exercises. Even though it’s late the questions are still interesting. I stumbled upon last task in extras and cannot figure out the solution.
The SQL scheme is as follows:
create table Movie(mID int, title text, year int, director text);
create table Reviewer(rID int, name text);
create table Rating(rID int, mID int, stars int, ratingDate date);
The whole database can be obtainted here
The question is the following:
Q12 For each director, return the director’s name together with the
title(s) of the movie(s) they directed that received the highest
rating among all of their movies, and the value of that rating.
Ignore movies whose director is NULL.
To give more specific details what’s the problem here:
One query
select m.mid, m.title, max(r.stars) as stars
from rating r natural join movie m
where m.director is NOT NULL group by m.mid
returns IDs of most rated movies:
101 Gone with the Wind 4
103 The Sound of Music 3
104 E.T. 3
107 Avatar 5
108 Raiders of the Lost Ark 4
Another query
select m.director, max(r.stars) as stars
from rating r natural join movie m
where m.director is NOT NULL group by m.director
returns names of the directors with most rated movies for them:
James Cameron 5
Robert Wise 3
Steven Spielberg 4
Victor Fleming 4
How to join the queries and get the name and stars for most rated movie for the director:
James Cameron Avatar 5
Robert Wise The Sound of Music 3
Steven Spielberg Raiders of the Lost Ark 4
Victor Fleming Gone with the Wind 4
In my opinion this is just a gretest-n-per-group problem. There is even a tag for that 🙂
The only difference with the typical situation is that the grouping data (director) is in one table and the data used to make the comparison is in another table (stars). So, if you look in the question tagged as such you should find similar examples.
I’d recommend you to solve it first assuming all your data is in one table (awful, but easier to solve… at least for me). And then switch to the splitted data.
Spoiler:
I think this is how to solve this so take a look at it only if you have already proposed a solution.