所以我有这张桌子
我想“打印”那些同一学期的学生的姓氏,但他们的成绩最低也是他们学期最高年级的2分。例如,对于第四学期,所需的姓氏是“Παπαβασιλείου”(最高等级= 9)和“Βαλκανιώτης”(等级= 7> =(9-2))
我所做的就是这段代码,但它不符合我的标准
SELECT GRADE as GRADE, SURNAME FROM pinakas2
WHERE GRADE >= ((SELECT MAX(GRADE) FROM pinakas2) - 2)
GROUP BY SEMESTER ORDER BY GRADE DESC
结果是:
答案 0 :(得分:1)
删除GROUP BY
,改为ORDER BY semester
:
SELECT GRADE as GRADE, SURNAME
FROM pinakas2
WHERE GRADE >= ((SELECT MAX(GRADE) FROM pinakas2) - 2)
ORDER BY SEMESTER, GRADE DESC
如果您希望每学期最高分数减去2,请改为执行相关的子查询:
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
答案 1 :(得分:0)
首先,您需要一个子查询来查找本学期的最高成绩,如下所示:
SELECT MAX(GRADE) GRADE, SEMESTER
FROM pinakas2
GROUP BY SEMESTER
然后你需要用它来检索你想要的学生:
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
如果由于某种原因您不关心发生这种情况的学期,请改为执行此操作。
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