Skip to main content

LeetCode 580. Count Student Number in Departments SQL Solution

Problem

LeetCode SQL Problem

  1. Count Student Number in Departments

student table

student_idstudent_namegenderdept_id
1JackM1
2JaneF1
3MarkM2

department table

dept_iddept_name
1Engineering
2Science
3Law
4Business

Solution

Count Student Number in Departments
-- Count student number in each department
-- Sort results by descending number of students and then department name
SELECT D.dept_name
,count(S.student_id) AS student_number
FROM department AS D
LEFT JOIN student AS S ON D.dept_id = S.dept_id
GROUP BY D.dept_name
ORDER BY count(S.student_id) DESC
,D.dept_name

Query Output

dept_namestudent_number
Engineering2
Science1
Business0
Law0