简体   繁体   中英

How to get multiple values of a column based on max value of another column?

So I have this table

在此处输入图片说明

I want to "print" the Surnames of those who are in the same semester but also their grade is maximum 2 points below their semester's highest grade. For example for the semester 4 the surnames needed are "Παπαβασιλείου" (highest grade = 9) and "Βαλκανιώτης" (grade = 7 >= (9 - 2))

what I've done is this code but it does not satisfy my criteria

SELECT GRADE as GRADE, SURNAME FROM pinakas2 
WHERE GRADE >= ((SELECT MAX(GRADE) FROM pinakas2) - 2) 
GROUP BY SEMESTER ORDER BY GRADE DESC

It gives as a result this:

在此处输入图片说明

Remove the GROUP BY , do ORDER BY semester instead:

SELECT GRADE as GRADE, SURNAME
FROM pinakas2 
WHERE GRADE >= ((SELECT MAX(GRADE) FROM pinakas2) - 2) 
ORDER BY SEMESTER, GRADE DESC

If you want highest grade per semester minus 2, do a correlated sub-query instead:

SELECT GRADE as GRADE, SURNAME
FROM pinakas2 p1
WHERE GRADE >= ((SELECT MAX(GRADE) FROM pinakas2 p2
                 where p1.semester = p2.semester) - 2) 
ORDER BY SEMESTER, GRADE DESC

First you'll need a subquery to find out the highest grade in the semester, as follows:

        SELECT MAX(GRADE) GRADE, SEMESTER
          FROM pinakas2
         GROUP BY SEMESTER

Then you need to use that to retrieve the students you want:

  SELECT a.GRADE, a.SURNAME, a.SEMESTER
    FROM pinakas2 a
    JOIN (
        SELECT MAX(GRADE) GRADE, SEMESTER
          FROM pinakas2
         GROUP BY SEMESTER
         ) b ON a.SEMESTER = b.SEMESTER AND a.GRADE >= b.GRADE - 2
   ORDER BY a.SURNAME, a.GRADE 

If for some reason you don't care about the semester in which this occurred, do this instead.

  SELECT DISTINCT a.GRADE, a.SURNAME
    FROM pinakas2 a
    JOIN (
        SELECT MAX(GRADE) GRADE, SEMESTER
          FROM pinakas2
         GROUP BY SEMESTER
         ) b ON a.SEMESTER = b.SEMESTER AND a.GRADE >= b.GRADE - 2
   ORDER BY a.SURNAME, a.GRADE 

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.

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