Given a Teacher table that contains information about teachers, subjects, and departments, write a SQL solution to calculate the number of unique subjects each teacher teaches in the university.
The table has the following structure:
teacher_id: The ID of the teachersubject_id: The ID of the subject being taughtdept_id: The ID of the department
Note that (subject_id, dept_id) forms the primary key, meaning each combination is unique. A teacher can teach the same subject in different departments, but we want to count each unique subject only once per teacher.
Return the result table in any order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
teacher_id
|
int | The ID of the teacher |
subject_id
PK
|
int | The ID of the subject being taught |
dept_id
PK
|
int | The ID of the department |
Input & Output
| 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 | 2 |
| teacher_id | cnt |
|---|---|
| 1 | 2 |
| 2 | 4 |
Teacher 1 teaches subject 2 in departments 3 and 4, and subject 3 in department 3. Since we count unique subjects, teacher 1 teaches 2 unique subjects (subjects 2 and 3). Teacher 2 teaches subjects 1, 2, 3, and 4, so they teach 4 unique subjects.
| teacher_id | subject_id | dept_id |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 1 | 3 |
| teacher_id | cnt |
|---|---|
| 1 | 1 |
Teacher 1 teaches the same subject (subject 1) in three different departments (1, 2, and 3). Since we only count unique subjects, the result is 1 unique subject.
| teacher_id | subject_id | dept_id |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| teacher_id | cnt |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
Each teacher teaches exactly one subject in one department, so each teacher has a count of 1 unique subject.
Constraints
-
1 ≤ teacher_id ≤ 10^5 -
1 ≤ subject_id ≤ 10^5 -
1 ≤ dept_id ≤ 10^5 -
(subject_id, dept_id)is the primary key of this table