找到三个标记中两个最大标记的平均值

时间:2018-02-18 07:08:33

标签: php mysql

我希望从三个系列标记中获得两个最高分的平均值。

以下是我尝试过的代码:

if(isset($_POST['find'])){
    $a=$_POST['a'];
    $ins=mysql_query("SELECT * 
                      FROM test1
                      WHERE studid ='$a'
                      ORDER BY mark DESC 
                      LIMIT 2");
    while($r=mysql_fetch_row($ins)){
        echo $r[2];
    }
}

1 个答案:

答案 0 :(得分:0)

查询应为:

  -- studid=1 top two average marks
  SELECT AVG(A.mark) avgTop2Marks FROM
  (SELECT mark
  FROM test1
  WHERE studid=1
  ORDER BY mark DESC 
  LIMIT 2) A;

  -- studid=1 distinct top two average marks
  SELECT AVG(A.mark) avgDistinctTop2Marks FROM
  (SELECT DISTINCT mark
  FROM test1
  WHERE studid=1
  ORDER BY mark DESC 
  LIMIT 2) A;

这是DEMO on SQL Fiddle.