I have a table as shown below. I am trying to get the grade, the highest numbers achieved on that grade and the student that got that high number.
name first_term_grade number
std1 A 10
std2 B 8
std3 A 6
std1 B 1
std2 C 3
std3 B 2
std1 C 0
std2 A 1
std3 C 2
The target result is shown below.
grade max_numbers studentname
A 10 std1
B 8 std2
C 3 std2
I am using MySQL but can't find a way around this. Can someone please put me through.
In MySQL 8+, ROW_NUMBER()
makes this easy:
SELECT first_term_grade AS grade, number AS max_numbers, name AS studentname
FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY first_term_grade ORDER BY number DESC) rn
FROM yourTable
) t
WHERE rn = 1
ORDER BY grade;
The above query says to retain one row for each letter grade having the highest number value.
If you you are running a release less than SQL 8, then:
select sq.*, the_table.name as studentname from (
select first_term_grade as grade, max(number) as max_numbers
from the_table
group by first_term_grade
) sq
join the_table on sq.grade = the_table.first_term_grade and sq.max_numbers = the_table.number
order by sq.grade
;
| grade | max_numbers | studentname |
| ----- | ----------- | ----------- |
| A | 10 | std1 |
| B | 8 | std2 |
| C | 3 | std2 |
Note that there could be ties, ie more than one student with the same grade and max_numbers.
| grade | max_numbers | studentname |
| ----- | ----------- | ----------- |
| A | 10 | std1 |
| A | 10 | std4 |
| B | 8 | std2 |
| C | 3 | std2 |
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.