2012-04-30 61 views
1

是否可以根據兩列的組合執行計數?使用兩個(或更多)列的COUNT

我有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,所以我道歉,如果這是基本的爲大家

回答

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 
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應確保每個班級只計算一次。

+0

謝謝你們。他們都工作:-) – user1361276