简体   繁体   中英

Postgresql getting other information from max tuple

Say you have a table with studentID, class, grade. I want the maximum grade for each class. This is easy, just group by class and get max(grade). But the problem I'm having is how to also get the studentID.

Instead of using an aggregate function, you could use window functions:

SELECT class, grade, studentId
FROM   (SELECT class, grade, studentId, 
               RANK() OVER (PARTITION BY class ORDER BY grade DESC) rk
        FROM   students)
WHERE  rk = 1

I think distinct on is a good way to go:

select distinct on (s.class) s.*
from students
order by s.class, s.grade desc;

However you probably want all students for each class with the maximum grade. If so, Mureinik's solution is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM