sql:在列出最小值、最大值、平均值和计数时遇到问题

iszxjhcz  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(468)

[1]: https://i.stack.imgur.com/r5pzz.png 我正在尝试列出每个assignmentid的最小值、最大值、平均值和计数。我用来创建图中所示内容的代码如下:

SELECT assignment.assignmentID, assignment.assignmentName, grade.grade

FROM grade 

JOIN assignment ON grade.assignmentID = assignment.assignmentID

当我在select函数中加入min,max,avg,count时,它只返回assignmentid 1的结果。我怎样才能让它完成所有的作业

a5g8bdjr

a5g8bdjr1#

我相信你想要:

SELECT a.assignmentID, a.assignmentName,
       COUNT(*) as numgrades, MIN(g.grade), MAX(g.grade), AVG(g.grade)
FROM assignment a JOIN
     grade g
     ON g.assignmentID = a.assignmentID
GROUP BY a.assignmentID, a.assignmentName;

您的查询缺少 GROUP BY 以及聚合函数。这是假设 grade 是数字,所以 AVG() 有道理。
注意,我还引入了表别名,因此查询更易于编写和读取。

kcwpcxri

kcwpcxri2#

那是因为你没有按分配记录分组。使用 group by 要在每个分配的基础上执行聚合,请执行以下操作:

select assignment.assignmentID, assignment.assignmentName,
    count(*) as gradeCount, avg(grade.grade) as avgGrade,
    min(grade.grade) as minGrade, max(grade.grade) as maxGrade
from assignment, grade
where assignment.assignmentID = grade.assignmentID
group by assignment.assignmentID, assignment.assignmentName

相关问题