File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,64 @@
1+
-- Problem:
2+
3+
/*
4+
Table: Teacher
5+
6+
+-------------+------+
7+
| Column Name | Type |
8+
+-------------+------+
9+
| teacher_id | int |
10+
| subject_id | int |
11+
| dept_id | int |
12+
+-------------+------+
13+
(subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table.
14+
Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.
15+
16+
17+
Write a solution to calculate the number of unique subjects each teacher teaches in the university.
18+
19+
Return the result table in any order.
20+
21+
The result format is shown in the following example.
22+
23+
24+
25+
Example 1:
26+
27+
Input:
28+
Teacher table:
29+
+------------+------------+---------+
30+
| teacher_id | subject_id | dept_id |
31+
+------------+------------+---------+
32+
| 1 | 2 | 3 |
33+
| 1 | 2 | 4 |
34+
| 1 | 3 | 3 |
35+
| 2 | 1 | 1 |
36+
| 2 | 2 | 1 |
37+
| 2 | 3 | 1 |
38+
| 2 | 4 | 1 |
39+
+------------+------------+---------+
40+
Output:
41+
+------------+-----+
42+
| teacher_id | cnt |
43+
+------------+-----+
44+
| 1 | 2 |
45+
| 2 | 4 |
46+
+------------+-----+
47+
Explanation:
48+
Teacher 1:
49+
- They teach subject 2 in departments 3 and 4.
50+
- They teach subject 3 in department 3.
51+
Teacher 2:
52+
- They teach subject 1 in department 1.
53+
- They teach subject 2 in department 1.
54+
- They teach subject 3 in department 1.
55+
- They teach subject 4 in department 1.
56+
*/
57+
58+
-------------------------------------------------------------------------------
59+
60+
-- Solution:
61+
162
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt FROM Teacher
263
GROUP BY teacher_id
364
ORDER BY teacher_id

0 commit comments

Comments
 (0)