-
leetcode - 580. Count Student Number in DepartmentsSQL 문제풀이 2022. 7. 1. 17:49
난이도 : Medium
Table: Student
+--------------+---------+ | Column Name | Type | +--------------+---------+ | student_id | int | | student_name | varchar | | gender | varchar | | dept_id | int | +--------------+---------+ student_id is the primary key column for this table. dept_id is a foreign key to dept_id in the Department tables. Each row of this table indicates the name of a student, their gender, and the id of their department.
Table: Department
+-------------+---------+ | Column Name | Type | +-------------+---------+ | dept_id | int | | dept_name | varchar | +-------------+---------+ dept_id is the primary key column for this table. Each row of this table contains the id and the name of a department.
Write an SQL query to report the respective department name and number of students majoring in each department for all departments in the Department table (even ones with no current students).
Return the result table ordered by student_number in descending order. In case of a tie, order them by dept_name alphabetically.
SELECT dept_name , COUNT(student_id) student_number FROM Department LEFT JOIN Student ON Department.dept_id = Student.dept_id GROUP BY dept_name ORDER BY student_number DESC, dept_name
Accepted (5.94%)
SELECT dept_name , COALESCE(student_num, 0) student_number FROM Department LEFT JOIN (SELECT dept_id , COUNT(student_id) student_num FROM student GROUP BY dept_id) sub ON Department.dept_id = sub.dept_id ORDER BY student_number DESC, Department.dept_name
Accepted (14.66%)
'SQL 문제풀이' 카테고리의 다른 글
leetcode - 1280. Students and Examinations (0) 2022.07.04 leetcode - 1251. Average Selling Price (0) 2022.07.04 leetcode - 578. Get Highest Answer Rate Question (0) 2022.07.01 leetcode - 1211. Queries Quality and Percentage (0) 2022.07.01 leetcode - 1179. Reformat Department Table (0) 2022.07.01