简体   繁体   中英

MySQL Query for Average Grade of last 2 attempts

I have a table:

quiz userid  attempt grade

1      3        1     33

1      3        2     67

1      3        3     90

1      3        4     20

Now, I want the last two attempts ie, 4 and 3 and I want average grade of these 2 grades ie, 90 and 20 Could anyone help me?

Use ORDER and LIMIT to get the 2 last attempts and the AVG aggregation function :

 SELECT AVG(grade) AS average FROM (
   SELECT grade FROM table 
   WHERE userid = 3
   ORDER BY attempt DESC LIMIT 2) AS t

If you want to list both test results separately, with the average in each row, then something like this maybe (otherwise you just need the subquery for the average of the two tests):

SELECT userid, attempt, grade, 

( SELECT AVG(grade)
    FROM table
      ORDER BY attempt DESC LIMIT 0, 2 ) AS avg_grade

FROM table
ORDER BY attempt DESC LIMIT 0, 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM