I am trying to write a query that lists students who have earned the highest total credit in each department. I have to also include tied students in the result. The query should return relation with department name, student name and total credit they earned.
SELECT s.dept_name, s.name, s.max FROM (SELECT dept_name, name, MAX(tot_cred) as max FROM university.student GROUP BY dept_name) as s, university.student as t WHERE s.name = t.name;
It is giving errors and I don’t know how to deal with ties. If I delete the name part in the query, I have managed to get the highest credits in each department(without a tie)
The table student consists of an ID, name, department, total credit.
Advertisement
Answer
Use RANK()
window function:
SELECT t.dept_name, t.name, t.tot_cred FROM ( SELECT dept_name, name, tot_cred, RANK() OVER(PARTITION BY dept_name ORDER BY tot_cred DESC) rn FROM university.student ) t WHERE t.rn = 1
This is an alternative in case you can’t use window functions:
SELECT s.dept_name, s.name, s.tot_cred FROM university.student s INNER JOIN ( SELECT dept_name, MAX(tot_cred) tot_cred FROM university.student GROUP BY dept_name ) t ON t.dept_name = s.dept_name AND s.tot_cred = t.tot_cred
or with NOT EXISTS
:
SELECT s.dept_name, s.name, s.tot_cred FROM university.student s WHERE NOT EXISTS ( SELECT 1 FROM university.student WHERE dept_name = s.dept_name AND tot_cred > s.tot_cred )