16. Unique Subjects per Teacher
At a university, teachers may teach the same subject in multiple departments, but for reporting purposes, the administration wants to know how many distinct subjects each teacher is responsible for, regardless of department.
You are given a Teacher table with the following columns:
βββββββββββββββ¦βββββββββββ β Column name β Type β β ββββββββββββββ¬βββββββββββ£ β teacher_id β int β βββββββββββββββΌβββββββββββ β subject_id β int β βββββββββββββββΌβββββββββββ β dept_id β int β βββββββββββββββ©βββββββββββ
- teacher_id: The ID of the teacher.
- subject_id: The ID of the subject being taught.
- dept_id: The department in which the subject is being taught.
(subject_id, dept_id) is the primary key of this table. Each row shows that a teacher teaches a specific subject in a department.
Write an SQL query to return the number of unique subjects taught by each teacher. The result can be returned in any order.
Example 1:
Example 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: Teaches subject 2 in departments 3 and 4 (counted once) and subject 3 in department 3 β Total = 2 unique subjects
- Teacher 2: Teaches subjects 1, 2, 3, 4 β All unique β Total = 4
Still unsure what the problem is asking ?
Letβs go through a few more examples, step by step, to make it clearer.