← Back to CTEs
Question 49
Students, Staff and Pay per Department
Students, Staff and Pay per Department
Build a one-row-per-department report from two CTEs:majorscounts students permajor_department_id(students with no major are not counted), andstaffcounts instructors perdepartment_idand averages theirsalary(rounded to 2 places). Join both todepartmentsand returndepartment(the name),students,instructorsandavg_salary, sorted bystudentsdescending, thendepartment. Aggregating inside the CTEs matters: joining the raw tables first would multiply the rows and inflate every figure.
Expected result:
+------------------+----------+-------------+------------+ | department | students | instructors | avg_salary | +------------------+----------+-------------+------------+ | Computer Science | 8 | 3 | 89500 | | Mathematics | 5 | 2 | 88750 | | Biology | 4 | 2 | 88000 | | Business | 4 | 2 | 92000 | | English | 4 | 2 | 81500 | | Fine Arts | 1 | 1 | 69000 | +------------------+----------+-------------+------------+ 6 rows
Hints4 available
Sign in to use hintsTopics:
CTEs
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Ctrl+Space to expand shortcuts (sel, ins, desc)
Results
Run your SQL to see every statement's output here, then how it compares with the expected answer.
Not sure what is in a table? SHOW TABLES lists them and DESCRIBE students shows the columns — or open the database browser on the left.