Number of Unique Subjects Taught by Each Teacher
Task: Write a solution to calculate the number of unique subjects each teacher teaches in the university.
Table: Teacher
| Column Name | Type |
|---|---|
| teacher_id | INT |
| subject_id | INT |
| dept_id | INT |
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 |
View Reference Solution & Explanation ▼
This solution uses the `GROUP BY` clause to aggregate results to find the required output.
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt FROM Teacher GROUP BY teacher_id;