1

是否可以根据两列的组合执行计数?

我有 3 张桌子:

学生: Student id | Student name | Gender | Dob |

班级登记:Student id | Class id

两列构成复合主键。

课程:Class id | Class name | Class day

我想计算每个班级中每种性别的学生人数。

到目前为止,我想出了这个查询:

SELECT class_name AS 'class Name',
  Child_gender AS 'Gender',
  COUNT(student_id) AS 'Count'
FROM student,classRegister,classes
WHERE student.student_id=classRegister.student_id AND
  classRegister.class_id=classes.class_id
GROUP BY class_name,student_gender
ORDER BY class_name;

但它似乎给了我一些学生重复的结果。

那么,我可以修改此查询以计算 和 组合的实例数student_idclass_id

我对 MySQL 还是很陌生,所以如果这对每个人来说都是基本的,我很抱歉

4

2 回答 2

1

试试这个:

SELECT c.class_name AS 'class Name', s.Child_gender AS 'Gender',
       COUNT(s.student_id) AS 'Count'
FROM student s
INNER JOIN classRegister cr ON s.student_id = cr.student_id 
INNER JOIN classes c ON cr.class_id = c.class_id
GROUP BY s.Child_gender, s.class_id, c.class_name
ORDER BY c.class_name
于 2012-04-30T15:00:48.537 回答
0
SELECT c.class_name AS 'class Name', s.Child_gender AS 'Gender',
       COUNT(DISTINCT s.student_id) AS 'Count'
FROM student s
INNER JOIN classRegister cr ON s.student_id = cr.student_id 
INNER JOIN classes c ON cr.class_id = c.class_id
GROUP BY c.class_name, s.Child_gender

如果他们在 classRegister 中有多个注册,您可能会多次获得同一个学生。这听起来很恶心。COUNT 中的 DISTINCT 应​​确保每个班级只计算一次。

于 2012-04-30T15:09:36.567 回答