MySQL获得平均值

时间:2014-05-23 14:30:40

标签: mysql

我的头晕了这个问题。 我有这样的表学生:

[teac_id] [less_id] [cl_id] [stu_id] [semester] [nilai_1] [nilai_2] [nilai_3] [nilai_4]
   3         3         1        1         1       90.00     90.00     90.00     null
   3         3         1        2         1       70.00     100.00    null      null

我使用复合主键,问题是如何得到这样的结果:

[teac_id] [less_id] [cl_id] [stu_id] [semester] [ AVG ]
   3         3         1       1        1         (nilai_1 + nilai_2 + nilai_3) / 3
   3         3         1       2        1         (nilai_1 + nilai_2) / 2

没有价值的领域不能成为一个除数。 谢谢提前。

1 个答案:

答案 0 :(得分:3)

如果数字nilai_字段已修复(即您有四个nilai_1..nilai_4),您可以尝试这样的事情(请注意,至少有一个字段不应为空) :

select teac_id, 
       less_id,
       cl_id, 
       stu_id,
       semester,
       -- average: just sum / count
       (IfNull(nilai_1, 0) + 
        IfNull(nilai_2, 0) +
        IfNull(nilai_3, 0) +
        IfNull(nilai_4, 0)) / 
        (if(nilai_1 is null, 0, 1) + 
         if(nilai_2 is null, 0, 1) +
         if(nilai_3 is null, 0, 1) +
         if(nilai_4 is null, 0, 1)) as AVG
  from MyTable

如果某个记录中的所有nilai_1..nilai_4为空,则必须修改查询:

select teac_id, 
       less_id,
       cl_id, 
       stu_id,
       semester,

       case 
         when (nilai_1 is null) and 
              (nilai_2 is null) and
              (nilai_3 is null) and
              (nilai_4 is null) then
           -- special case: all nulls average
           null
         else
           -- average: just sum / count
          (IfNull(nilai_1, 0) + 
           IfNull(nilai_2, 0) +
           IfNull(nilai_3, 0) +
           IfNull(nilai_4, 0)) / 
             (if(nilai_1 is null, 0, 1) + 
              if(nilai_2 is null, 0, 1) +
              if(nilai_3 is null, 0, 1) +
              if(nilai_4 is null, 0, 1)) 
       end as AVG
  from MyTable