我有考試成績這是一個表,如下所示:甲骨文 - 獲得最新最好的結果的子集的
CREATE TABLE tbl (
studentid INT,
examid INT,
score INT,
attempt INT,
percentcorrect INT
);
現在對每一個學生,我需要提取他最好的考試成績(由percentcorrect測量) ,並且如果考試已經完成了兩次,對於給定的學生同樣的最佳分數,應該顯示最新嘗試的記錄。我已經完成了雙嵌套查詢(首先選擇最高的百分比正確,然後從最終的集合,然後其餘的數據最大嘗試),但我希望有更高效的方法來實現這一點。有任何想法嗎?
編輯: 我的查詢:
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;
請發表您的疑問和樣本數據的幾行。 –