有人知道如何在其他查询的基础上选择每个组的最大值吗?
示例表:
Class Exam Grade
Math1 Mid 1
Math2 Mid 2
Math1 Final 1
说我有这样的第一个查询:
SELECT *
FROM table
WHERE Class = 'Math1'
现在使用结果表我想按照考试分组,只保留最高等级的行:
SELECT view1.*
FROM
(SELECT *
FROM table
WHERE Class = 'Math1') AS view1, view2
WHERE view1.Exam = view2.Exam
AND view1.Grade > view2.Grade
问题我无法为同一个表提供2个别名。所以view1和view2不会按照写的方式工作。有最好的做法吗? 谢谢!
更新 谢谢大家的答案,它帮助了我,但我试图用WITH来记住以下解决方案:
WITH view AS (SELECT *
FROM table
WHERE Class = 'Math1)
SELECT view1.*
FROM view view1, view view2
WHERE view1.Exam = view2.Exam
AND view1.Grade > view2.Grade
答案 0 :(得分:0)
为什么不:
SELECT distinct max(grade) over (partition by exam), exam
FROM table
WHERE Class = 'Math1'
答案 1 :(得分:0)
如果您想要成绩最高的行,请使用def tempValid(self, cureTemp):
temp = int(self.cureTemp.get())
if temp <= 219:
self.delete_and_focus()
return lowTempMsg(self)
elif temp >= 261:
return rejMsg(self)
else:
return()
和order by
:
limit
答案 2 :(得分:0)
您可以使用row_number
为所有Math
课程选择每个考试成绩最高的行
select * from (
select *,
row_number() over (partition by exam, Class order by grade desc) rn
where Class = 'Math1'
) t where rn = 1
如果您想包含最高等级的关系,请使用rank
代替row_number
答案 3 :(得分:0)
您可以使用distinct on
为每项考试选择具有最高成绩的行:
select distinct on (exam) exam,
t.*
from (
-- Your query here
select *
from table
where class = 'Math1'
) t
order by exam,
grade desc;
或直接:
select distinct on (exam) exam,
t.*
from table
where class = 'Math1'
order by exam,
grade desc;