MySQL查询最近2次尝试的平均等级

时间:2011-12-17 08:07:07

标签: mysql

我有一张桌子:

quiz userid  attempt grade

1      3        1     33

1      3        2     67

1      3        3     90

1      3        4     20

现在,我想要最后两次尝试,即4和3,我想要这两个等级的平均等级,即90和20 有谁可以帮助我?

2 个答案:

答案 0 :(得分:1)

使用ORDERLIMIT获取最后2次尝试以及AVG aggregation function

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

答案 1 :(得分:0)

如果你想单独列出两个测试结果,每行的平均值,那么这样的事情可能(否则你只需要两个测试的平均值的子查询):

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;