简体   繁体   English

MySQL:在 window function 中使用 MAX 不返回最高值

[英]MySQL: Using MAX in a window function not returning highest values

I am seeking to find the highest grade scores for each student_id.我正在寻找每个 student_id 的最高成绩。 The grade scores are kept in this table:成绩分数保存在此表中:

Enrollments table:招生表:

student_id学生卡 course_id course_id grade年级
2 2 2 2 95 95
2 2 3 3 95 95
1 1 1 1 90 90
1 1 2 2 99 99
3 3 1 1 80 80
3 3 2 2 75 75
3 3 3 3 82 82

The correct result should be:正确的结果应该是:

student_id学生卡 course_id course_id grade年级
1 1 2 2 99 99
2 2 2 2 95 95
3 3 3 3 82 82

Here is the query I am trying:这是我正在尝试的查询:

SELECT student_id, course_id, grade
 FROM Enrollments
 GROUP BY student_id
 HAVING grade = (SELECT MAX(grade) OVER(PARTITION BY student_id))
 ORDER BY student_id ASC    

However with this query, the results I'm getting are:但是,通过此查询,我得到的结果是:

student_id学生卡 course_id course_id grade年级
1 1 2 2 90 90
2 2 2 2 95 95
3 3 3 3 80 80

ie student 1's grade is 90, when it should be 99, and student 2's grade is 80, when it should be 82.即学生1的成绩是90,应该是99,学生2的成绩是80,应该是82。

It seems like the issue is this query is only selecting the max grade from the first course_id in the table, but I'm not sure why that would be the case.似乎问题是该查询仅从表中的第一个 course_id 中选择最高成绩,但我不确定为什么会这样。

Please try this query.请尝试此查询。

SELECT e.student_id, e.course_id, e.grade
FROM Enrollments e INNER JOIN 
(SELECT student_id as student_id, MAX(grade) as grade FROM Enrollments GROUP BY student_id) sbq 
ON e.student_id = sbq.student_id
WHERE e.grade = sbq.grade;

You can use row_number, for your desired result您可以使用 row_number,以获得您想要的结果

CREATE TABLE Table1 (`student_id` int, `course_id` int, `grade` int);
 INSERT INTO Table1 (`student_id`, `course_id`, `grade`) VALUES (2, 2, 95), (2, 3, 95), (1, 1, 90), (1, 2, 99), (3, 1, 80), (3, 2, 75), (3, 3, 82);
 SELECT `student_id`, `course_id`, `grade` FROM (SELECT `student_id`, `course_id`, `grade`, ROW_NUMBER() OVER(PARTITION BY `student_id` ORDER BY `grade` DESC) rn FROM Table1) t1 WHERE rn= 1
 student_id |学生ID | course_id | course_id | grade ---------: |等级------: | --------: | --------: | ----: 1 | ----: 1 | 2 | 2 | 99 2 | 99 2 | 2 | 2 | 95 3 | 95 3 | 3 | 3 | 82 82

db<>fiddle here db<> 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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