我需要编写一个SQL查询来返回所有电影的平均评分,而这些电影中的每一个都是“浪漫”,而不是“喜剧”。
下面是我的表格列表->
create table genres (genreid int,
name text,
primary key(genreid));
create table ratings(userid int,
movieid int,
rating numeric check(rating<=1 OR rating<=5),
timestamp bigint,
PRIMARY KEY (userid,movieid),
FOREIGN KEY (userid) REFERENCES users (userid),
FOREIGN KEY (movieid) REFERENCES movies (movieid));
create table hasagenre( movieid int,
genreid int,
FOREIGN KEY (movieid) REFERENCES movies (movieid),
FOREIGN KEY (genreid) REFERENCES genres (genreid));
我尝试了以下代码,但得到的答案错误
FROM ratings R,hasagenre H1,hasagenre H2,genres G1,genres G2
WHERE R.movieid=H1.movieid AND H1.genreid=G1.genreid
AND R.movieid=H2.movieid AND H2.genreid=G2.genreid
AND (G2.name <> 'Comedy' AND G1.name = 'Romance');
预期平均值:3.7429411764705882 实际结果:3.7458333333333333
如果我想获得所有电影的平均收视率,并且每部电影都是“浪漫”和“喜剧”,那么上面的代码可以很好地工作,方法是将<>'Comedy替换为='Comedy'
答案 0 :(得分:0)
SELECT avg(R.rating)
FROM ratings R
WHERE movieid IN ( SELECT movieid
FROM hasagenre H
JOIN genres G
ON H.genreid = G.genreid
GROUP BY movieid
HAVING COUNT( CASE WHEN G.name = 'Comedy' THEN 1 END) = 1
AND COUNT( CASE WHEN G.name = 'Romance' THEN 1 END) = 0 )