在一个SQLite数据库表中,有两列'mID'和'stars'。我需要返回具有最高平均值'stars'的'mID'。
以下是数据: 评分 mID stars 101 2 101 4 106 4 103 2 108 4 108 2 101 3 103 3 104 2 108 4 107 3 106 5 107 5 104 3
我首先要通过按'mID'分组来计算每个'mID'的'stars'的平均值,例如:
因此,我将获得每个'mID'的平均“星级”值表。
因此,我使用了'not exists'关键字,后跟生成另一个'mID'和'stars'表的子查询。 这个子查询与原始表进行比较,以验证对于来自原始表R1的某个平均“星级”值,不存在新表R2的平均“星级”值大于R1的平均“星级”值。
我原本以为这个查询可以得到所有电影的平均评分和它们的mID,但实际上我得到的是两个元组 ('mID':106, 'theAvg':4.5) 和 ('mID':107, 'theAvg':4.0),而期望的答案只有一个元组 ('mID':106, 'theAvg':4.5),因为我们要找的是所有'stars'的平均值中最高的一个。
我的错误查询结果: mID theAvg 106 4.5 107 4.0 期望的查询结果: mID theAvg 106 4.5
您认为我做错了哪些步骤?您有什么建议吗?
以下是数据: 评分 mID stars 101 2 101 4 106 4 103 2 108 4 108 2 101 3 103 3 104 2 108 4 107 3 106 5 107 5 104 3
我首先要通过按'mID'分组来计算每个'mID'的'stars'的平均值,例如:
select mID, avg(stars) theAvg
from Rating
group by mID;
因此,我将获得每个'mID'的平均“星级”值表。
mID avg(stars) 101 3.0 103 2.5 104 2.5 106 4.5 107 4.0 108 3.33333333333如果我只返回最高的“星级”平均值, 那么我可以像选择max(theAvg)一样接着我刚刚计算的内容。 但是,为了获得与其'mID'相关联的最高平均“星级”,我需要其他东西。
因此,我使用了'not exists'关键字,后跟生成另一个'mID'和'stars'表的子查询。 这个子查询与原始表进行比较,以验证对于来自原始表R1的某个平均“星级”值,不存在新表R2的平均“星级”值大于R1的平均“星级”值。
select mID, theAvg
from (select mID, avg(stars) theAvg
from Rating
group by mID) as R1
where not exists(select * from
(select mID, avg(stars) theAvg
from Rating
group by mID) as R2
where R2.theAvg > R1.theAvg);
我原本以为这个查询可以得到所有电影的平均评分和它们的mID,但实际上我得到的是两个元组 ('mID':106, 'theAvg':4.5) 和 ('mID':107, 'theAvg':4.0),而期望的答案只有一个元组 ('mID':106, 'theAvg':4.5),因为我们要找的是所有'stars'的平均值中最高的一个。
我的错误查询结果: mID theAvg 106 4.5 107 4.0 期望的查询结果: mID theAvg 106 4.5
您认为我做错了哪些步骤?您有什么建议吗?