嗨,所以我正在做一个小型的爱好项目,我正在尝试让GROUP BY子句正常工作,但它不是对结果进行分组而是只需要一列。
示例:
Table classes ( guID, className )
Table student ( guID, name, classID)
Table grades ( s_id, c_id, grade)
例如,返回整个班级的某个等级的编号:
生:
"Alex", "class1"
"Kevin", "class1"
"Lisa", "class2"
等级:
"alex_id", "course_id", "B"
"alex_id", "course_id", "A"
"kevin_id", "course_id", "A"
"lisa_id", "course_id", "C"
QUERY:
SELECT classes.className, (SELECT COUNT(*) FROM grades WHERE s_id = student.guID AND grade = "A") as Total_Grades
FROM classes
INNER JOIN student
ON classes.guID = student.classID
WHERE classes.guID = 1
GROUP BY classes.className;
这只会给出结果:
"class1", 1
它应该给出的地方:
"class1", 2
如果有人有空闲时间,我会感激一些帮助。
答案 0 :(得分:2)
我将告诉你如何通过两个步骤实现目标
假设您只想显示成绩数,可以执行以下查询。
SELECT count(*)
FROM grades g
WHERE g.c_ID = 1 and g.grade = 'A'
如果我们想要包含className,我们需要添加group by子句,因为我们要将className字段添加到输出中。任何不在聚合函数中的东西都需要进入group by子句。
SELECT c.className, count(*)
FROM grades g
JOIN classes c
ON g.c_id = c.guID
WHERE c.guID = 1 and g.grade = 'A'
GROUP BY classes.className