为我提供了以下数据库:
movie(movie_id, movie_name, production_year, votes, ranking, rating)
movie_info(movie_id, movie_genre_id, note)
movie_genre(movie_genre_id, genre_name)
person(person_id, person_name, gender)
role(person_id, movie_id, role_name, role_type_id)
role_type(role_type_id, type_name)
要求我显示列表中至少有3部电影的前7名导演的姓名,所处电影的数量以及其电影的平均收视率(按平均收视率排序)。在下面的查询中,我设法获得了导演的姓名,所处电影的数量和平均评级,但是我遇到了将其限制在前7名并按平均评级对它们进行排序的问题。我尝试使用LIMIT和ORDER BY,但是出现语法错误。
SELECT
person_name, COUNT(role.movie_id), AVG(rating)
FROM
movie
INNER JOIN
role
ON role.movie_id = movie.movie_id
INNER JOIN
person
ON role.person_id = person.person_id
INNER JOIN
role_type
ON role.role_type_id = role_type.role_type_id
WHERE
type_name = 'director'
GROUP BY
person_name
HAVING
COUNT(role.movie_id) > 2;
我什至可以按他们拍摄的电影数量进行排序,并将其限制在前7名,但是对于上帝,我无法按AVG(评级)进行排序
person_name COUNT(role.movie_id) AVG(rating)
Hitchcock, Alfred 9 8.2888890372382
Kubrick, Stanley 8 8.2999999523163
Wilder, Billy 6 8.3000000317891
Spielberg, Steven 6 8.4000000953674
Scorsese, Martin 6 8.3166666030884
Nolan, Christopher 6 8.5333331425985
Tarantino, Quentin 6 8.3666666348775
答案 0 :(得分:0)
Select
,Group By
和Order By
子句的Having
子句can be used中定义的别名。Order by .. DESC
对结果集进行降序排序,使用Limit 7
仅获得7行。Group By
上使用person_id
,因为在某些情况下董事的姓名相同。role
表中有重复的条目,则必须使用Count(Distinct ...)
以避免计算重复的行。尝试以下查询:
SELECT
p.person_id,
p.person_name,
COUNT(r.movie_id) AS movies_count,
AVG(m.rating) AS average_rating
FROM
movie AS m
INNER JOIN
role AS r
ON r.movie_id = m.movie_id
INNER JOIN
person AS p
ON r.person_id = p.person_id
INNER JOIN
role_type AS rt
ON r.role_type_id = rt.role_type_id
WHERE
rt.type_name = 'director'
GROUP BY
p.person_id,
p.person_name
HAVING
movies_count > 2
ORDER BY
movies_count DESC,
average_rating DESC
LIMIT 7