← Back to Window Functions
Question 56
Top Two Students in Each Major
Top Two Students in Each Major
Find the two students with the highestgpain every major. In a CTE namedranked, joinstudentstodepartmentsand number each student within theirmajor_department_idwithROW_NUMBER()bygpadescending (ties broken byid), skipping NULL gpas. Then returndepartment(the department name),first_name,last_name,gpaandrnfor the rows numbered 1 or 2, sorted bydepartment, thenrn. Undeclared students belong to no major, and Fine Arts has only one student.
Expected result:
+------------------+------------+-----------+------+----+ | department | first_name | last_name | gpa | rn | +------------------+------------+-----------+------+----+ | Biology | Harper | Singh | 3.55 | 1 | | Biology | Isabella | Okoro | 3.1 | 2 | | Business | Abigail | Larsen | 3.3 | 1 | | Business | Mason | Nguyen | 3.25 | 2 | | Computer Science | Grace | Lee | 3.88 | 1 | | Computer Science | Ava | Patel | 3.8 | 2 | | English | Mia | Haddad | 3.8 | 1 | | English | Zoe | Campbell | 3.5 | 2 | | Fine Arts | Scarlett | Johnson | 3.6 | 1 | | Mathematics | Evelyn | Park | 3.98 | 1 | +------------------+------------+-----------+------+----+ (showing 10 of 11 rows)
Hints4 available
Sign in to use hintsTopics:
Window Functions
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.