mysql sql avg函数不返回正确的值?

时间:2017-05-22 09:26:34

标签: mysql sql

I've my table with structure like this

现在我想制作一个表格,用公式显示每个学生的最终平均成绩:

Final_avg=0.15x(average of exam= test1,test2 and test3) 
         +0.25x(exam=midterm)+0.6x(exam=terminal);

我已尝试此查询,但我收到的fainal_avg值不正确

select e.sname AS sn 
     , AVG( CASE WHEN e.exam IN ('test1','test2','test4') THEN e.average END )  AS t_avg
     , e3.average as mid
     , e2.average as main
     , 0.15*e.average+0.25*e3.average+0.6*e2.average AS f_avg 
  from $form as e 
  JOIN $form as e2 
    ON e2.sname = e.sname AND e2.exam = 'terminal'
  JOIN $form as e3 
    ON e3.sname = e.sname AND e3.exam = 'midterm'
 group by e.sname 
 order by f_avg  desc

我从查询中获得的最终平均值是一个无限的,我通过使用计算器计算得到的

This is table for correct and incorrect final average

2 个答案:

答案 0 :(得分:1)

您按e.sname分组,但在select子句中访问e.average。由于每个sname有几个记录,因此DBMS从中选择哪个值是偶然的。在您的情况下,您希望使用AVG(e.sname)之类的聚合:AVG(CASE WHEN e.exam IN ('test1','test2','test4') THEN e.average END)

然而,这种自连接和条件聚合的混合有点笨拙。我建议您在加入之前汇总您的测试记录,或者根本不加入。

加入前汇总测试记录

select
  sname, 0.15 * tst.average + 0.25 * mid.average + 0.6 * trm.average as result
from
(
  select sname, avg(average) as average
  from $form
  where exam in ('test1','test2','test4')
  group by sname
) tst
join $form trm on trm.sname = tst.sname and exam = 'terminal'
join $form mid on mid.sname = tst.sname and exam = 'midterm';

仅仅聚合,没有加入

select
  sname, 
  0.15 * avg(case when exam in ('test1','test2','test4') then average end) + 
  0.25 * avg(case when exam = 'midterm' then average end) + 
  0.6 * avg(case when exam = 'terminal' then average end) as result
from $form
group by sname;

答案 1 :(得分:0)

它返回给定参数的平均值,即表的字段名称。 Distinct选项可用于计算给定值集中唯一值的平均值。 如果我们要从学生表中找到平均分数,则在s_marks列中给出分数。 For More Click