我正在处理SQL作业问题:
“对于每部评分至少为1的电影,请查找电影标题和星级总数,最高星级以及给出最高星级的人。”
数据库:
create table Movies(mID integer, title varchar(100));
create table Reviewers(rID integer, name varchar(100));
create table Ratings(rID integer, mID integer, stars integer);
insert into Movies values(101, 'Gone with the Wind');
insert into Movies values(102, 'Star Wars');
insert into Movies values(103, 'The Sound of Music');
insert into Reviewers values(201, 'Sarah Martinez');
insert into Reviewers values(202, 'Daniel Lewis');
insert into Reviewers values(203, 'Brittany Harris');
insert into Ratings values(201, 101, 2);
insert into Ratings values(203, 101, 4);
insert into Ratings values(203, 102, 4);
insert into Ratings values(203, 103, 4);
insert into Ratings values(202, 103, 2);
我能提出的最佳查询是:
SELECT title,
SUM(stars) AS total_stars,
MAX(stars) AS highest_stars,
name AS highest_stars_reviewer
FROM Movies
INNER JOIN Ratings USING(mID)
INNER JOIN Reviewers USING(rID)
GROUP BY mID;
问题在于,查询不返回给出最高星星评论的评论者的姓名,而是返回具有较低rID的评论者,该评论者评论了电影。
希望此查询对您有所帮助,以得到所需的结果。
答案 0 :(得分:1)
在SQL中执行此操作的正确方法是使用窗口函数:
SELECT m.title,
SUM(r.stars) AS total_stars,
MAX(r.stars) AS highest_stars,
MAX(CASE WHEN r.seqnum = 1 THEN rv.name END) AS highest_stars_reviewer
FROM Movies m INNER JOIN
(SELECT r.*,
ROW_NUMBER() OVER (PARTITION BY m.id ORDER BY r.stars DESC) as seqnum
FROM Ratings r
) r
USING (mID) INNER JOIN
Reviewers rv
USING (rID)
GROUP BY m.title, m.mID;
注意:
GROUP BY
列应与SELECT
列匹配-尽管您的版本还可以,因为在聚合键是唯一键的情况下,SQL允许您执行此操作。