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.

Hints

0
Β 
Test Case

Input:

Teacher