2017-05-29 66 views
0

我有一个sql语句的问题,我必须平均5个笔记,但只要字段已满,我有字段f1,f2,f3,f4,如果f1和f3已满我的选择必须添加f1和f3并将其除以2,但如果f1,f2和f4已满,您必须添加并将其除以3,我试过CASE但它不起作用,它只是总是留下一个案例。在选择句子中的情况

这是我的代码:

SELECT b.nombreAlumno As 'Alumno', f1 as 'F1' ,f2 as 'F2',f3 as 'F3',f4 as 'F4',sumativa as 'Sumativa', 
'Promedio' = Case 
when f1 > 0 then @promedio=(f1 + sumativa)/2 
when f2 > 0 then (f1 + f2 + sumativa)/3 
when f3 > 0 then (f1 + f2 + f3 + sumativa)/4 
when f4 > 0 then (f1 + f2 + f3 + f4 + sumativa)/5 
End 

FROM tbNotas a,tbalumnos b 
WHERE [email protected] and [email protected] and [email protected] and a.idalumno=b.idalumno and [email protected] 
and [email protected] 

我的数据 F1 10 F2 8.67 F3 10 F4 0 sumativa 1

结果5.5(这是不好的,因为将要加10 + 8.67 + 10 + 1/4 => 7.4)

感谢您的帮助。

+0

你使用了哪个数据库? –

+0

Sql Server我使用 –

回答

0

假设值为0或空当你想忽略他们,你可以这样做:

select ((coalesce(f1, 0) + coalesce(f2, 0) + coalesce(f3, 0) + coalesce(f4, 0) + coalesce(f5, 0)) * 1.0/
     (coalesce(f1 > 0, 0) + coalesce(f2 > 0, 0) + coalesce(f3 > 0, 0) + coalesce(f4 > 0, 0) + coalesce(f5 > 0, 0)) 
     ) as average 

如果该值只对0而不是NULL,并不需要coalesce()秒。

编辑:

上面是MySQL。更一般的解决方案是:

select (((case when f1 > 0 then f1 else 0 end) + 
      (case when f2 > 0 then f2 else 0 end) + 
      (case when f3 > 0 then f3 else 0 end) + 
      (case when f4 > 0 then f4 else 0 end) + 
      (case when f5 > 0 then f5 else 0 end) 
     )/
     nullif((case when f1 > 0 then 1.0 else 0 end) + 
       (case when f2 > 0 then 1 else 0 end) + 
       (case when f3 > 0 then 1 else 0 end) + 
       (case when f4 > 0 then 1 else 0 end) + 
       (case when f5 > 0 then 1 else 0 end), 0 
       ) 
     ) 
+0

太棒了!在sql server中工作得很好,但是我必须显示2位小数,并且将舞台(如小数点(5,2))作为舞台和工作区?你知道为什么吗?很多。 –

+0

现在正在进行整数除法。尝试乘以1.0的分子,使其浮动'1.0 *((CASE ....' –