🤔 문제 분석
1) Write an SQL query to report the type of each node in the tree.
Each node in the tree can be one of three types:
- "Leaf": if the node is a leaf node.
- "Root": if the node is the root of the tree.
- "Inner": If the node is neither a leaf node nor a root node.
Write an SQL query to report the type of each node in the tree.
2) Return the result table in any order.
![[리트코드/SQL] 13. Tree node (608) [리트코드/SQL] 13. Tree node (608)](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
![[리트코드/SQL] 13. Tree node (608) [리트코드/SQL] 13. Tree node (608)](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
💡 풀이
SELECT
distinct t1.id,
CASE
WHEN t1.p_id IS NULL THEN "Root"
WHEN t2.id IS NOT NULL THEN "Inner"
ELSE "Leaf"
END AS "type"
FROM Tree AS t1
LEFT JOIN Tree AS t2 ON t1.id = t2.p_id
'코딩테스트 > 리트코드 SQL' 카테고리의 다른 글
[리트코드/SQL] 15. Combine Two Tables (175) (0) | 2022.12.18 |
---|---|
[리트코드/SQL] 14. Second Highest Salary (176) (0) | 2022.12.16 |
[리트코드/SQL] 12. Rearrange Products Table (1795) (0) | 2022.12.16 |
[리트코드/SQL] 11. Employees With Missing Information (1965) (0) | 2022.12.16 |
[리트코드/SQL] 10. Patients With a Condition (1527) (0) | 2022.12.08 |
댓글