如何在mysql workbench

时间:2016-11-19 15:52:44

标签: mysql

对于每个学生,找到他们选择的课程数量并进行排序 行按降序排列。 (例如学生ID,数量 该学生参加的课程)

STUDENT TABLE

| ID      | name      | dept_name      | tot_cred |
| S0901   | Alice     | Comp.Sci.      | 83       |
| S0902   | Martha    | Comp.Sci.      | 75       |
| S0903   | Micheal   | Comp.Sci.      | 45       |
| S0904   | Rose      | Comp.Sci.      | 77       |
| S0905   | Alfie     | Comp.Sci.      | 91       |
| S1901   | Brad      | Biology        | 23       |

TAKES TABLE

| ID      | course_id      | sec_id      | semester      | year      | grade      
| S0901   | CS-101         | 1           | Fall          | 2009      | A          
| S0901   | CS-315         | 1           | Spring        | 2010      | B+         
| S0901   | HIS-351        | 1           | Spring        | 2010      | A-         
| S0901   | MTH-101        | 1           | Fall          | 2009      | A          
| S0901   | MTH-102        | 1           | Spring        | 2009      | B+   
| S0902   | CS-101         | 1           | Fall          | 2009      | A          
| S0902   | CS-315         | 1           | Spring        | 2010      | B+         
| S0902   | CS-319         | 1           | Spring        | 2010      | B          
| S0902   | HIS-351        | 1           | Spring        | 2010      | A-         
| S0902   | MTH-101        | 1           | Fall          | 2009      | A          
| S0902   | MTH-102        | 1           | Spring        | 2009      | B+         
| S1901   | CS-101         | 1           | Fall          | 2009      | B+         
| S1901   | CS-190         | 1           | Spring        | 2009      | C          
| S1901   | CS-315         | 1           | Spring        | 2010      | A-         
| S1901   | HIS-351        | 1           | Spring        | 2010      | A-    

2 个答案:

答案 0 :(得分:1)

从技术上讲,@ Marcinek的答案可能不够,因为它省略了零课程的学生。我会改用它:

SELECT STUDENT.ID, COUNT(TAKES.ID)
FROM STUDENT LEFT JOIN TAKES ON STUDENT.ID = TAKES.ID
GROUP BY STUDENT.ID
ORDER BY COUNT(TAKES.ID) DESC;

通过使用LEFT JOIN,您可以捕获ID未出现在TAKES表中的学生。

答案 1 :(得分:0)

只需加入并对结果进行分组。

SELECT COUNT(*), s.id FROM student s, takes t where t.id = s.id group by s.id order by count(*) desc