Strange MySQL AVG() anomaly NULL values

前端 未结 5 990
小蘑菇
小蘑菇 2020-12-08 21:27

What I\'am doing :

create table sample (id INT(10) PRIMARY KEY AUTO_INCREMENT,name varchar(255),marks INT(10));

insert into sample (name,marks) VALUES(\'sam         


        
5条回答
  •  无人及你
    2020-12-08 22:01

    That's the normal behaviour, since NULL is not zero. How do you make the average of 5 + NULL? So MySQL is taking only the rows that can be averaged.

    Appart from the correct answers other users have already given you, you can also use the COALESCE function, which returns the first non-NULL value you specify in the list, so you can replace the NULL one with the one you like:

        SELECT AVG(COALESCE(marks,0)) FROM sample GROUP BY(name);
    

提交回复
热议问题