2017-05-29 12 views
0

SQLステートメントに問題がありますが、平均5つのメモが必要ですが、フィールドがいっぱいである限り、フィールドf1、f2、f3、f4があり、f1とf3が完全な場合selectは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 8.67 F3 10 F4 0 sumativa 1

は5.5(10 + 8.67を追加する必要がありますので、それは悪い結果10 F2 + 10 + 1/4 => 7.4)

ご協力いただきありがとうございます。値を仮定

+0

どのデータベースをお使いですか? –

+0

Sql Server私は –

答えて

0

が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 
       ) 
     ) 
+0

を使います! SQL Serverでうまく動作しますが、小数点以下2桁を表示する必要があり、小数点以下の桁数(5,2)としてキャストをプロンプトとdowsnの仕事として使用しますか?なぜなのかご存知ですか? thaks a lot。、 –

+0

今は整数除算を実行しています。あなたの分子に1.0を乗じてみましょう。 '1.0 *((CASE ....' –

関連する問題