从具有相同主键的一定数量的行中,如何 select 某一列中具有最高值的行?

From a certain number of rows with the same primary key, how do I select the ones with the highest value in a certain column?

我有一个学生 table 和一个成绩 table。

"Grades" 看起来像这样:

student_id|course_id|grade
===========================
    1     |    1    |   A
    1     |    2    |   B
    1     |    3    |   A
    3     |    1    |   F
    3     |    3    |   C
    .
    .
    .
    .

这不是全部 table,但您明白了要点。我正在尝试编写一个查询来选择学生的姓名和该学生的最高成绩。由于我是 SQL 的新手,所以这个让我有点困惑。到目前为止,我的尝试是这样的:

SELECT "Students".name, "Grades".grade FROM "Students" INNER JOIN
"Grades" ON "Students".student_id = "Grades".student_id GROUP BY name, 
grade HAVING MIN(grade) <= 'F';

这是错误的,我知道为什么,但我不确定从这里去哪里。

SELECT Students.name, min(Enroll.grade)  
  FROM Students 
 INNER JOIN Enroll 
    ON Students.student_id = Enroll.student_id 
 GROUP BY name, 

how do I select the ones with the highest value in a certain column?

大胆强调我的。

GROUP BY 可以很好地获得单列的最大值。要获得最大值的 ,您必须做更多。

在 Postgres 中获得每个学生 一个 行的简单解决方案是 DISTINCT ON:

SELECT *
FROM   students s
JOIN  (
   SELECT DISTINCT ON (student_id) *
   FROM   grades
   ORDER  BY student_id, grade
   ) g USING (student_id);

最低恰好是这里的"highest"等级。
要得到the ones with the highest value(可能复数),使用window函数rank():

SELECT *
FROM   students s
JOIN  (
   SELECT *, rank() OVER (PARTITION BY student_id ORDER BY grade) AS rnk
   FROM   grades
   ) g USING (student_id)
WHERE  g.rnk = 1;