在具有两列“mID”和“stars”的 SQLite 数据库表中,我必须返回“stars”平均值最高的“mID”。
有以下数据:
Rating
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”的“星星”平均值,例如
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
如果我只返回“星星”的最高平均值,
那么我可以只采取类似 select max(theAvg) 的东西,然后是我刚刚计算的结果。
但是,为了获得与其“mID”相关的最高平均“星星”,我需要其他东西。
因此,我使用了“不存在”关键字,后跟一个子查询,该子查询生成另一个“mID”和“星星”表。
该子查询与原始表进行比较,以验证对于原始表 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'平均值的最高平均值。
The result of my query(Wrong):
mID theAvg
106 4.5
107 4.0
The desired Result:
mID theAvg
106 4.5
你认为我哪些步骤错了?有什么建议你会怎么做吗?