2013-07-23 33 views
0

我有考試成績這是一個表,如下所示:甲骨文 - 獲得最新最好的結果的子集的

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; 
+2

請發表您的疑問和樣本數據的幾行。 –

回答

4

Analytical RANK function可以用於此:

SELECT studentid, examid, score 
FROM (
    SELECT 
    studentid, 
    examid, 
    score, 
    attempt, 
    RANK() OVER (
     PARTITION BY studentid, examid 
     ORDER BY score DESC, attempt DESC) AS ScoreAttemptRank 
    FROM tbl 
) 
WHERE ScoreAttemptRank = 1 

這個查詢將返回的最好成績每個學生/每次考試的最新嘗試。如果您不考慮考試,只需要每個學生的最佳考試分數,請將PARTITION BY studentid, examid更改爲PARTITION BY studentid

0

您可以使用Comman Table Expression(https://forums.oracle.com/thread/921467)和OVER(http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm)來獲得結果。下面的查詢是w.r.t SQL Server,我們在Oracle中也有同樣的東西。還用於識別同一考試最新考試成績,我有ExamDate表

;WITH CTE_StudentResult 
      AS (SELECT StudentId , 
         PercentCorrect , 
         ROW_NUMBER() OVER (PARTITION BY StudentId ORDER BY percentcorrect DESC, ExamDate DESC) AS RowNumber 
       FROM  tbl 
      ) 
    SELECT StudentId , 
      PercentCorrect 
    FROM CTE_StudentResult 
    WHERE RowNumber = 1 
0

試試這個

SELECT DISTINCT * FROM tbl 
WHERE (studentid, percentcorrect, attempt) IN (
     SELECT studentid, percentcorrect, MAX (attempt) 
     FROM tbl 
     WHERE (studentid, percentcorrect) IN (SELECT studentid,MAX (percentcorrect)FROM tbl GROUP BY studentid) 
     GROUP BY studentid, percentcorrect)