我的数据库中有这个表:
classes
id | classname |
grades
id | class_id | grade | date
我需要根据日期+正确的班级名称获得成绩和最新成绩的平均值。
我有这个查询,但这不会输出正确的类名...
SELECT
AVG(grade),
classes.classname,
grades.grade,
MIN(ABS(DATEDIFF(CURDATE(),'date')))
FROM
grades, classes
GROUP BY
grades.grade_id
ORDER BY grades.date DESC
答案 0 :(得分:1)
你的问题似乎有点茫然,所以我回答了我对你问题的解释。
你没有证明你得到了什么,但是,我猜你会得到一份平均成绩列表,而不是有成绩的班级。
所以,虽然我认为那里有几个问题。第一
select avg(grade), classname from classes
left join grade on classes.id = grades.class_id
group by classname
应该按类提供平均成绩。
什么是cijfers?你并没有真正包括很多,但你还要求它以某种方式平均。
答案 1 :(得分:0)
首先,AVG(cijfer)实际上没有引用任何内容。您需要将AVG()分配给这样的变量:
AVG(grade) AS avgrade
也许您可以尝试这样的查询:
SELECT AVG(grade) as average FROM grades, class_id AS cid, (SELECT classname FROM classes WHERE id=cid) AS cname FROM grades ORDER BY date DESC GROUP BY cname;
如何运作?
答案 2 :(得分:0)
尽管我讨厌为他们做某人的功课,但这似乎对我有用:
select a.classname, AVG(b.grade) AS "Avg Grade", c.grade as "Most Recent Grade", c.grade_date as "Most Recent Grade Date" from classes a, grades b, grades c where a.id = b.class_id AND c.class_id = a.id AND NOT EXISTS (SELECT d.grade_date FROM grades d WHERE d.class_id = c.class_id AND d.grade_date > c.grade_date) group by a.classname, c.grade, c.grade_date;