2013-02-10 74 views
0

以下查詢(針對教育應用)計算用戶對特定演練的分數。它適用於四個表格 - 用戶,演練,問題和答案。每個問題屬於演習,每個答案屬於一個問題和一個用戶(答案對用戶和問題是唯一的)。如果answer.selectedChoice = 1,問題是多項選擇並且答案是正確的。用戶的演練評分取決於該演練的最近五次答案,並且分配給正確答案的權重根據答案的速度縮放。如何擴展SQL計算查詢以給出多個父行的結果

我想弄清楚如何擴展這個查詢,這樣,而不是僅僅得到一個特定鑽的用戶的分數,我可以得到每個鑽的用戶的分數,他們已經回答了至少一個問題。我一直在調查重寫它作爲相關的子查詢,但到目前爲止,我的努力已經不足。任何幫助將不勝感激。

SELECT data.*, 
    SUM(data.isCorrect * (IF(rawScore < 0, 0, IF(rawScore > 1, 1, rawScore))))/5 AS score 
FROM 
    (SELECT 
     answer.id, 
     IF(answer.selectedChoice = 1, 1, 0) AS isCorrect, 
     (1 - (answer.timeElapsed - question.baseTime)/(4 * question.baseTime)) as rawScore 
    FROM 
     answer, 
     question 
    WHERE 
     answer.questionID = question.id AND 
     question.drillID = :drillID AND 
     answer.userID = :userID 
    ORDER BY 
     answer.created DESC 
    LIMIT 
     5) as data 

回答

0

請嘗試以下。假設「他們已經回答了至少一個問題」條件,您正在使用answer.created列。 這個想法是得到一個用戶的所有問題,並計算isCorrect,rawScore,得分(如果情況下)你需要的任何數據,並通過question.drillID,answer.userID(用戶的每個鑽頭的得分)分組,然後使用HAVING子句只獲得至少回答一個問題的用戶(他們至少回答了一個問題)。

下面的查詢可能會給你錯誤的結果 - 請張貼表結構和樣本數據,我可以爲你創建一個演示。

SELECT 
    answer.id, 
    IF(answer.selectedChoice = 1, 1, 0) AS isCorrect, 
    (1 - (answer.timeElapsed - question.baseTime)/(4 * question.baseTime)) as rawScore 
-- SUM(data.isCorrect * (IF(rawScore < 0, 0, IF(rawScore > 1, 1, rawScore))))/5 AS score 
-- SUM(IF(answer.selectedChoice = 1, 1, 0) * (IF(1 - (answer.timeElapsed - question.baseTime)/(4 * question.baseTime)) < 0, 0, IF((1 - (answer.timeElapsed - question.baseTime)/(4 * question.baseTime)) > 1, 1, (1 - (answer.timeElapsed - question.baseTime)/(4 * question.baseTime))))))/5 AS score 
FROM answer a 
INNER JOIN question q ON answer.questionID = question.id 
GROUP BY 
    question.drillID, answer.userID 
WHERE 
    answer.userID = :userID 
HAVING 
    COUNT(answer.created) >= 1;