This is a basic extract of the film rental platform I'm working on. To show you, I just need these three tables.
Film
Title | Genre |
-------------+---------------+
Why Me | Romantic |
The ET | Fantasy |
... | ... |
Planet | Documentary |
User
ID | Name |
-------------+---------------+
213 | Jonh D |
34267 | Smith E |
... | ... |
256 | Sally F |
Rent
User_ID | Film_Title | Date |
-------------+---------------+-------------+
34267 | The ET | 2015-11-01 |
256 | Planet | 2014-12-03 |
... | ... | ... |
256 | Why Me | 2016-03-04 |
That said, I need to do a SQL query that associates to each Film.Genre
the User.Name
that have rented the highest amount of films for that genre.
ID | Genre |
-------------+---------------+
Sally F | Romantic |
Smith E | Fantasy |
... | ... |
Sally F | Documentary |
I would have posted some of my attempts but honestly I didn't come out with anything which is barely sense making. I know that using JOIN
statement would be easier that trying to build it with nested statements but I am stumped and this is so frustrating.
SELECT u.Name, f.Genre
FROM User AS u JOIN Rent AS r JOIN Film AS f
GROUP BY f.Genre
ORDER BY(COUNT(r.User_ID))
This is assuming that the genre field is in your rentals table:
select user_id, genre, max(rentals) from
(select
user_id,
genre,
count(*) as rentals
from rent group by user_id, genre)
group by user_id, genre;
You could use a subquery like this one:
SELECT sub.Name, sub.Genre, MAX(rent_number)
FROM (
SELECT User.Name, Film.Genre, Count(User.ID) as rent_number
FROM Film
INNER JOIN Rent ON Film.Title = Rent.Film_Title
INNER JOIN User ON Rent.User_ID = User.ID
GROUP BY User.Name, Film.Genre) sub
GROUP BY sub.Genre
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.