[英]Calculate the Average of several marks excluding null values
SQL novice and in need of help. SQL新手,需要帮助。 I am trying to calculate the average of the 4 subjects, however if a subject is null/0 then for it not to be included in the calculation.
我正在尝试计算4个主题的平均值,但是,如果一个主题为null / 0,则该主题将不包含在计算中。
Type Collation
Student_ID varchar(5)
Surname varchar(9)
First_Name varchar(7)
Ballet int(2)
Contemporary int(2)
Jazz int(2)
Tap int(2)
I have been able to get the average in a view using the below but cannot figure out how to solve the null/0
issue. 我已经能够使用以下方法在视图中获得平均值,但无法弄清楚如何解决
null/0
问题。
SELECT Student_ID, Surname, First_Name, BALLET_1, CONTEMPORARY_1, JAZZ_1, TAP_1, sum(BALLET_1+CONTEMPORARY_1+JAZZ_1+TAP_1 )/4 as Avg from tblassesstest group by Surname
SELECT
(
SELECT COALESCE( nb1, 0 ) + COALESCE( nb2, 0 ) + COALESCE( nb3, 0 ) as ADDITION
)
/
(
SELECT
COALESCE(nb1 /nb1, 0)
+
COALESCE(nb2 /nb2, 0)
+
COALESCE(nb3 /nb3, 0)
AS DIVIDEBY
) AS AVG
FROM YOURTABLE
I think this is the best worse answer. 我认为这是最好的最坏答案。 Explanations :
说明:
The function COALESCE replace your NULL by another value, here 0. 函数COALESCE用另一个值(这里为0)替换NULL。
The second select (DIVIDEBY) count the number of columns which are not null : 第二个选择(DIVIDEBY)计算不为null的列数:
The top "anonymous" SELECT send each column (nb1, nb2, nb3) to the two sub requests for the selected Table (YOURTABLE) 顶部的“匿名” SELECT将每一列(nb1,nb2,nb3)发送到选定表(YOURTABLE)的两个子请求
SELECT Student_ID, Surname, First_Name, BALLET_1, CONTEMPORARY_1, JAZZ_1, TAP_1, SELECT Student_ID,姓,名,BALLET_1,CONTEMPORARY_1,JAZZ_1,TAP_1,
(
SELECT COALESCE( BALLET_1, 0 ) + COALESCE( CONTEMPORARY_1, 0 ) + COALESCE( JAZZ_1, 0 )+ COALESCE( TAP_1, 0 ) as ADDITION
)
/
(
SELECT
COALESCE(COALESCE(BALLET_1, 0) / COALESCE(BALLET_1, 0), 0)
+
COALESCE(COALESCE(CONTEMPORARY_1, 0) / COALESCE(CONTEMPORARY_1, 0), 0)
+
COALESCE(COALESCE(JAZZ_1, 0) / COALESCE(JAZZ_1, 0), 0)
+
COALESCE(COALESCE(TAP_1, 0) / COALESCE(TAP_1, 0), 0)
AS DIVIDEBY
) AS AVG
FROM tblassesstest 从tblassstest
group by Surname 按姓氏分组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.