Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择句中的格_Sql_Sql Server_Tsql_Case - Fatal编程技术网

Sql 选择句中的格

Sql 选择句中的格,sql,sql-server,tsql,case,Sql,Sql Server,Tsql,Case,我对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', 'Promedi

我对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   idquimestre=@quimestre and idParcial=@parcial and idmateria=@materia and a.idalumno=b.idalumno and a.idparalelo=@paralelo
and a.idcurso=@idcurso
我的数据 f1 10 f2 8.67 f3 10 f4 0 sumativa 1

结果5.5(这很糟糕,因为应该加上10+8.67+10+1/4=>7.4)


谢谢你的帮助

如果要忽略它们,则假设该值为0或NULL,您可以执行以下操作:

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()
s

编辑:

以上是针对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
               )
         )

你用的是什么数据库?Sql Server我用的很好!!!在sql server中工作得很好,但我必须显示2个小数,我将cast(作为十进制(5,2))作为prom和dowsn工作??你知道为什么吗?thaks很多,现在正在执行整数除法。尝试将分子乘以1.0,使其浮动
1.0*((大小写…