MySQL Query for Average of last 2 attempts

后端 未结 5 1418
悲&欢浪女
悲&欢浪女 2021-01-23 07:27

I have a table:

quiz userid  attempt grade

1      3        1     33

2      3        1     67

1      3        2     90

10     3        4     20

2      3              


        
5条回答
  •  春和景丽
    2021-01-23 08:12

    Makes 2 assumption: that all you attempts are sequential and have no voids (Ie 1,2,3,4) exists and not 1,3,4,6) IF the latter, I can correct. (will use a limit/order descending)

    assumes you want the avg of the 2 grades per person/per quiz.

    Explanation: Executes a sub query to : get quiz, user where attempt is equal to max attempt for the same quiz/user less 1. Performance isn't ideal there is likely a faster way but this shold work.

    SELECT T1.quiz, T1.userID, avg(T1.grade)
    FROM TABLE T1
       T1.Attempt >= 
        (Select max(T3.attempt) -1
         from table T3
         where T3.QUIZ=T1.Quiz 
         AND T3.UserID=T1.UserID)
    GROUP BY T1.Quiz, T1.UserID
    

提交回复
热议问题