Coding Challenges/LeetCode

[SQL50] 596. Classes More Than 5 Students

기록해연 2025. 3. 5. 09:20

난이도: EASY

 

문제 링크: https://leetcode.com/problems/classes-more-than-5-students/description/?envType=study-plan-v2&envId=top-sql-50


문제

더보기

Table: Courses
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| student     | varchar |
| class       | varchar |
+-------------+---------+
(student, class) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.

Write a solution to find all the classes that have at least five students.
Return the result table in any order.
The result format is in the following example.

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 별로 / 몇 개씩 있는지 수를 세서 / 5개 보다 같거나 큰 class를 / 출력.

GROUP BY class / HAVING COUNT(class) =< 5 / SELECT

 

 


 

나의 최종 제출 답안:

SELECT class
FROM Courses
GROUP BY class    
HAVING COUNT(class) >= 5

 

 


 

chatGPT와의 대화:

나: 이 문제를 풀 때 일반적으로 COUNT(*)와 COUNT(student)와 COUNT(class) 중에 뭘 쓰는게 맞아?

 

GPT:

세 컬럼 모두 이 테이블에서는 NULL 값이 없으므로, 기술적으로는 COUNT(*)와 COUNT(student), COUNT(class) 모두 같은 결과를 반환합니다. 다만, 관례와 의도를 고려할 때는 다음과 같이 선택할 수 있습니다.

  • COUNT(*): 그룹 내의 모든 행(레코드)을 세므로, 일반적으로 "행 수"를 셀 때 가장 많이 사용됩니다.
  • COUNT(student) 또는 COUNT(class): 해당 컬럼의 NULL이 아닌 값의 수를 센다는 의미로, 특정 컬럼에 초점을 맞출 때 사용합니다.

이 문제에서 각 행은 한 학생의 수업 등록을 나타내므로, "학생 수"를 구하는 목적에 더 명확하게 부합하는 것은 COUNT(*)입니다.
또한, COUNT(*)는 테이블의 모든 행을 세므로, NULL 값 처리에 대해 걱정할 필요가 없다는 장점이 있습니다.

따라서 일반적으로 이 문제를 풀 때는 COUNT(*)를 사용하는 것이 가장 적합하고, 가독성과 의도 전달 면에서도 좋습니다.