[SQL 문제 풀이] Tree Node (트리 노드)

Stupefyee's avatar
May 19, 2025
[SQL 문제 풀이] Tree Node (트리 노드)
Number of Unique Subjects Taught by Each Teacher - LeetCode
Can you solve this real interview question? Number of Unique Subjects Taught by Each Teacher - Table: Teacher +-------------+------+ | Column Name | Type | +-------------+------+ | teacher_id | int | | subject_id | int | | dept_id | int | +-------------+------+ (subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table. Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.   Write a solution to calculate the number of unique subjects each teacher teaches in the university. Return the result table in any order. The result format is shown in the following example.   Example 1: 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: - They teach subject 2 in departments 3 and 4. - They teach subject 3 in department 3. Teacher 2: - They teach subject 1 in department 1. - They teach subject 2 in department 1. - They teach subject 3 in department 1. - They teach subject 4 in department 1.
Number of Unique Subjects Taught by Each Teacher - LeetCode
notion image
트리의 각 노드는 세 가지 유형 중 하나일 수 있습니다: * "리프": 노드가 리프 노드인 경우. * "루트": 노드가 트리의 루트인 경우. * "내부": 노드가 리프 노드도 루트 노드도 아닌 경우. 트리의 각 노드 유형을 보고하는 솔루션을 작성하세요. 결과 테이블을 순서에 상관없이 반환하세요.
 

내가 작성한 쿼리

MySQL, Oracle

SELECT id, CASE WHEN p_id IS NULL THEN 'Root' WHEN id IN (SELECT p_id FROM tree) THEN 'Inner' ELSE 'Leaf' END AS type FROM tree;
Share article

stupefyee