1. 程式人生 > >MySQL基礎之 統計函式總結

MySQL基礎之 統計函式總結

五種統計函式:count()、max()、avg()、min()、max()函式

count()函式

count()函式在進行計算的時候,是分情況進行計算的,主要是一下兩種

1、採用count(*)對錶中的記錄進行統計,不管表字段中包含的是NULL值還是非NULL值,都會參與計算

2、而採用count(field)方式對錶中的記錄進行統計,如果所在的field中包含有NULL值,將忽略NULL值。

舉例所示:

mysql> select * from test1_1;          #可以看出來表中一共有6條記錄,其中有條記錄的name列包含NULL值
+----+--------+
| id | name | +----+--------+ | 1 | 超峰 | | 2 | b | | 3 | c | | 4 | a | | 5 | chen | | 6 | NULL | +----+--------+ 6 rows in set (0.00 sec) mysql> select count(*) from test1_1; +----------+ | count(*) | +----------+ | 6 | +----------+ 1 row in set (0.00 sec) mysql>
select count(name) from test1_1; #NULL值將不參與計算 +-------------+ | count(name) | +-------------+ | 5 | +-------------+ 1 row in set (0.00 sec)

 

sum()函式

sum()函式實現統計指定欄位值之和,在具體統計時將忽略NULL值,但是不會忽略0值

舉例子:

mysql> select * from test1_1;
+----+--------+-------+
| id | name   | grade |
+----+--------+-------+ | 1 | 超峰 | 99 | | 2 | b | 90 | | 3 | c | 95 | | 4 | a | 85 | | 5 | chen | 90 | | 6 | NULL | 90 | +----+--------+-------+ 6 rows in set (0.00 sec) mysql> select sum(grade) from test1_1; +------------+ | sum(grade) | +------------+ | 549 | +------------+ 1 row in set (0.00 sec) mysql> update test1_1 set grade=NULL where id=6; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from test1_1; +----+--------+-------+ | id | name | grade | +----+--------+-------+ | 1 | 超峰 | 99 | | 2 | b | 90 | | 3 | c | 95 | | 4 | a | 85 | | 5 | chen | 90 | | 6 | NULL | NULL | +----+--------+-------+ 6 rows in set (0.00 sec) mysql> select sum(grade) from test1_1; #會發現NULL值沒有參與計算 +------------+ | sum(grade) | +------------+ | 459 | +------------+ 1 row in set (0.00 sec)

 

MAX()和MIN()函式

MAX函式和MIN函式會忽略值為NULL的資料,但是不會忽略值為0的資料

在此不做舉例

 

針對沒有任何資料的表,這五種函式的返回值是什麼呢?

舉例子:

mysql> select * from test1_5;
Empty set (0.00 sec)

mysql> select count(*),avg(id),sum(id),max(id),min(id) from test1_5;
+----------+---------+---------+---------+---------+
| count(*) | avg(id) | sum(id) | max(id) | min(id) |
+----------+---------+---------+---------+---------+
|        0 |    NULL |    NULL |    NULL |    NULL |
+----------+---------+---------+---------+---------+
1 row in set (0.00 sec)

看的出來只有count函式的返回值是0,其他的函式返回值都是NULL。