난이도: EASY
문제
Table: Teacher
+-------------+------+
| Column Name | Type |
+-------------+------+
| teacher_id | int |
| subject_id | int |
| dept_id | int |
+-------------+------+
(subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table.
Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.
Write a solution to calculate the number of unique subjects each teacher teaches in the university.
Return the result table in any order.
The result format is shown in the following example.
Example 1:
Input:
Teacher table:
+------------+------------+---------+
| teacher_id | subject_id | dept_id |
+------------+------------+---------+
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 1 | 3 | 3 |
| 2 | 1 | 1 |
| 2 | 2 | 1 |
| 2 | 3 | 1 |
| 2 | 4 | 1 |
+------------+------------+---------+
Output:
+------------+-----+
| teacher_id | cnt |
+------------+-----+
| 1 | 2 |
| 2 | 4 |
+------------+-----+
Explanation:
Teacher 1:
- They teach subject 2 in departments 3 and 4.
- They teach subject 3 in department 3.
Teacher 2:
- They teach subject 1 in department 1.
- They teach subject 2 in department 1.
- They teach subject 3 in department 1.
- They teach subject 4 in department 1.
시도 1
SELECT teacher_id, COUNT(subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
중복된 값 안 합쳐서 틀림.
=> DISTINCT 처리
나의 최종 제출 답안:
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
'Coding Challenges > LeetCode' 카테고리의 다른 글
[SQL50] 596. Classes More Than 5 Students (0) | 2025.03.05 |
---|---|
[SQL50] 1141. User Activity for the Past 30 Days I (1) | 2025.03.04 |
[SQL50] 1280. Students and Examinations (0) | 2025.02.20 |
[SQL50] 577. Employee Bonus (0) | 2025.02.19 |
[Java] 28. Find the Index of the First Occurrence in a String (1) | 2025.02.14 |