I'm stuck with an SQL query. I know what to do but I can't figure out how. So, here is the scheme needed:
Movie (title, director, year, genre, rate);
TITLE DIRECTOR YEAR GENRE RATE
Fight club Fincher 1999 Action 4.5
Vertigo Hitchock 1958 Drama 5
Donnie darko Kelly 2001 Thriller 3.5
Video(title, director, colloc);
TITLE DIRECTOR COLLOC
Fight club Fincher 3877
Fight club Fincher 3878
Vertigo Hitchcock 5431
Vertigo Hitchcock 5432
Donnie darko Kelly 9986
Rent(colloc, dateRent, customer, dateReturn);
COLLOC DATERENT CUSTOMER DATERETURN
3877 2016-05-02 324 2016-05-04
3877 2016-05-20 365 2016-05-20
3878 2016-04-11 876 2016-04-12
3878 2016-06-06 112 2016-06-08
... ... ... ...
... ... ... ...
9986 2016-02-24 443 2016-02-28
And here is the query:
List, for each movie, how many videos were rented at least two times.
(Note: the store generally has more videos - dvds, vhs, etc. - for each movie).
My approach is the following: I would start with this simple query
SELECT colloc, title, director, COUNT(colloc) AS rentNumber
FROM Rent
NATURAL JOIN Video
GROUP BY colloc
To display something like this:
COLLOC TITLE DIRECTOR RENTNUMBER
3877 Fight club Fincher 2
3878 Fight club Fincher 2
5432 Vertigo Hitchcock 2
5431 Vertigo Hitchcock 1
9986 Donnie darko Kelly 1
In order to get to this:
TITLE DIRECTOR VIDEOSNUMBER
Fight club Fincher 2
Vertigo Hitchcock 1
Donnie darko Kelly 0
But I'm missing this last step, I can't appropriately use GROUP BY / HAVING. No success even with subqueries. I've been trying to use a different approach but I came out with nothing good, so any tips would be appreciated.
Thanks.
Edit: NOTE, there's no need to use the table Movie in the query. I put it there just to explain that a movie can have more than one video. Added table examples. Primary keys are in bold.
SOLUTION: Thanks to your tips i found a solution (to be honest it's partial, since it lets out all the films for which there are no videos that were rented at least 2 times). Anyway, here it is:
SELECT title, director, COUNT(title) AS videosNumber
FROM (SELECT colloc, title, director, COUNT(colloc) AS rentNumber
FROM rent NATURAL JOIN video
GROUP BY colloc
) X
WHERE rentNumber > 1
GROUP BY title
VIDEOSNUMBERmeans in your expected output?