Question

SQL novice and in need of help. 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.

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.

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
Était-ce utile?

La solution

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.

  • The first select (ADDITION), do the sum between each columns and add 0 instead of NULL
  • The second select (DIVIDEBY) count the number of columns which are not null :

    • It add 1 when column are not NULL or equal to 0. (This is why the column is divide by itself.)
    • It add 0 when the column is NULL or equal 0.
  • The top "anonymous" SELECT send each column (nb1, nb2, nb3) to the two sub requests for the selected Table (YOURTABLE)

  • The two sub request are divided for each row in order to obtain the average (AVG)
  • The AVG request is the column of the top "anonymous" SELECT

Autres conseils

SELECT Student_ID, Surname, First_Name, 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
group by Surname

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top