![](/img/trans.png)
[英]How do I select the highest column value in an SQL query IF another column is equal to a certain string
[英]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?
我有一个学生表和一个成绩表。
“成绩”如下所示:
student_id|course_id|grade
===========================
1 | 1 | A
1 | 2 | B
1 | 3 | A
3 | 1 | F
3 | 3 | C
.
.
.
.
这不是整张桌子,但要点。 我正在尝试编写一个查询,该查询选择一个学生的姓名和该学生的最高成绩。 由于我是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,
如何在特定列中选择具有最高价值的商品?
大胆强调我的。
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);
最低的恰好是这里的“最高”等级。
要获得the ones with the highest value
(可能是复数 )的the ones with the highest value
,请使用窗口函数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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.