SQL

[Leetcode/SQL] 596. Classes More Than 5 Students

지구인 ㅣ 2022. 8. 20. 23:50

728x90
문제는 여기서 확인할 수 있습니다.

Table: Courses

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| student     | varchar |
| class       | varchar |
+-------------+---------+
(student, class) is the primary key column for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.

 

순서 무관하게, 수강생이 5명 이상인 클래스(과목)을 반환하라.

 

Example 1:

Input: 
Courses table:
+---------+----------+
| student | class    |
+---------+----------+
| A       | Math     |
| B       | English  |
| C       | Math     |
| D       | Biology  |
| E       | Math     |
| F       | Computer |
| G       | Math     |
| H       | Math     |
| I       | Math     |
+---------+----------+
Output: 
+---------+
| class   |
+---------+
| Math    |
+---------+
Explanation: 
- Math has 6 students, so we include it.
- English has 1 student, so we do not include it.
- Biology has 1 student, so we do not include it.
- Computer has 1 student, so we do not include it.

class가 대상이기 때문에 class 기준으로 grouping을 합니다.

그리고 각 class의 student를 count하면 됩니다. 다만, class, *를 넣어도 결과는 같습니다. class, *를 넣을 경우, group by class를 미리 해주었기 때문에 class별 전체 row를 세는 것과 같고 이는 student를 세더라도 마찬가지입니다. 따라서 같은 결과가 나왔다고 할 수 있습니다.

 

Code:

select class
from Courses
group by class
having count(student) >= 5  # student 대신 class, *를 넣어도 결과는 같다.

 

728x90