我的表类似于命名为'score':

我想查询所有cno及其对应的平均学位,该学位至少有5名学生(sno表示学生数量),从3开始。
我尝试了以下查询语句:
select cno,avg(degree) from score where cno in (select cno from score group by cno HAVING count(1) > 5 ) and cno like '3%';但是,它抛出了一个错误。
我的MySql版本是8.0.18
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'practice01.score.Cno' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Error code 1055.发布于 2019-12-31 18:09:01
您可以简单地执行以下操作:
select cno, avg(degree) from score
where cno like '3%'
group by cno
HAVING count(cno) >= 5出现此错误的原因是,当MySql的only_full_group_by模式打开时,使用GROUP BY时将应用严格的ANSI SQL规则。这意味着对一个列执行group by,可以选择其他列的聚合函数。
其他列的“聚合”表示对另一列使用聚合函数,如MIN()、MAX()或AVG()。
希望这能有所帮助。
由于您在子查询中使用group by,而在外部查询中未使用group by,因此会出现错误。
发布于 2019-12-31 18:09:22
您不需要子查询-您可以将having条件应用于相同的查询:
SELECT cno, AVG(degree)
FROM score
WHERE cno LIKE '3%'
GROUP BY cno
HAVING COUNT(*) >= 5发布于 2019-12-31 18:13:57
select cno, avg(degree) from score
group by cno HAVING count(cno) > 5 ) and cno like '3%';在执行group by之后,您可以像count, sum etc一样在having子句中对分组的行查询aggregate
https://stackoverflow.com/questions/59542573
复制相似问题