简体   繁体   English

计算不包含空值的几个标记的平均值

[英]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 first select (ADDITION), do the sum between each columns and add 0 instead of NULL 首先选择(ADDITION),在各列之间求和,然后加0而不是NULL
  • The second select (DIVIDEBY) count the number of columns which are not null : 第二个选择(DIVIDEBY)计算不为null的列数:

    • It add 1 when column are not NULL or equal to 0. (This is why the column is divide by itself.) 当列不为NULL或等于0时,它加1。(这就是列被自身除的原因。)
    • It add 0 when the column is NULL or equal 0. 当列为NULL或等于0时,它加0。
  • 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)的两个子请求

  • The two sub request are divided for each row in order to obtain the average (AVG) 为每行划分两个子请求,以获得平均值(AVG)
  • The AVG request is the column of the top "anonymous" SELECT AVG请求是顶部“匿名” SELECT的列

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM