我有一张包含考试结果的表格,如下所示:
CREATE TABLE tbl (
studentid INT,
examid INT,
score INT,
attempt INT,
percentcorrect INT
);
现在,对于每个学生,我需要提取他的最佳考试成绩(以正确率衡量),如果给定的考试以相同的最佳成绩完成了两次,则应显示最新尝试的记录。我已经用双重嵌套查询完成了它(首先选择最高百分比正确,然后从结果集中选择最大尝试,然后是其余数据),但我希望有更有效的方法来实现这一点。有任何想法吗?
编辑:我的查询:
SELECT
result.score
, r2.attempt
, r2.percentcorrect
, r2.studentid
, r2.examid
FROM
tbl result JOIN
(
SELECT
res.studentid
, res.examid
, r.percentcorrect
, MAX(res.attempt) AS attempt
FROM
tbl res JOIN
(
SELECT studentid, examid, MAX(percentcorrect) AS percentcorrect
FROM tbl
GROUP BY studentid, examid
) r ON r.studentid = res.studentid
AND r.examid = res.examid
AND r.percentcorrect = res.percentcorrect
GROUP BY
res.studentid
, res.examid
, r.percentcorrect
ORDER BY res.examid
) r2
ON r2.studentid = result.studentid
AND r2.examid = result.examid
AND r2.percentcorrect = result.percentcorrect
AND r2.attempt = result.attempt
一些样本数据:
INSERT ALL
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(1,1,30,1,10)
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(1,1,20,2,15)
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(2,1,80,1,100)
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(2,1,80,2,90)
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(3,2,10,1,9)
INTO tbl(studentid, examid, percentcorrect, attempt, score)
VALUES(3,3,15,1,100)
SELECT * FROM DUAL; COMMIT;