关于分组函数/聚合函数/多行处理函数
| count | 
取得记录数 | 
| avg | 
取平均 | 
| sum | 
求和 | 
| max | 
取最大数 | 
| min | 
取最小数 | 
具体运用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
   | MariaDB [hello]> select max(sal) from emp; +----------+ | max(sal) | +----------+ |  5000.00 | +----------+ 1 row in set (0.001 sec) //最大值应用 MariaDB [hello]> select min(sal) from emp; +----------+ | min(sal) | +----------+ |   800.00 | +----------+ 1 row in set (0.000 sec) //最小值应用 MariaDB [hello]> select sum(sal) from emp; +----------+ | sum(sal) | +----------+ | 29025.00 | +----------+ 1 row in set (0.000 sec) //总和应用 MariaDB [hello]> select avg(sal) from emp; +-------------+ | avg(sal)    | +-------------+ | 2073.214286 | +-------------+ 1 row in set (0.001 sec) //平均值应用 MariaDB [hello]> select count(sal) from emp; +------------+ | count(sal) | +------------+ |         14 | +------------+ 1 row in set (0.001 sec) //取得记录数应用
 
  | 
 
注意事项
第一点:分组函数自动忽略NULL,不需要提前对NULL进行处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | MariaDB [hello]> select ename,comm from emp; +--------+---------+ | ename  | comm    | +--------+---------+ | SMITH  |    NULL | | ALLEN  |  300.00 | | WARD   |  500.00 | | JONES  |    NULL | | MARTIN | 1400.00 | | BLAKE  |    NULL | | CLARK  |    NULL | | SCOTT  |    NULL | | KING   |    NULL | | TURNER |    0.00 | | ADAMS  |    NULL | | JAMES  |    NULL | | FORD   |    NULL | | MILLER |    NULL | +--------+---------+ 14 rows in set (0.001 sec) MariaDB [hello]> select sum(comm) from emp; +-----------+ | sum(comm) | +-----------+ |   2200.00 | +-----------+ 1 row in set (0.001 sec) //可见对NULL自动忽略。
 
  | 
 
第二点:分组函数中count(*)和count(具体字段)有什么区别?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | MariaDB [hello]> select count(*) from emp; +----------+ | count(*) | +----------+ |       14 | +----------+ 1 row in set (0.001 sec)
  MariaDB [hello]> select count(comm) from emp; +-------------+ | count(comm) | +-------------+ |           4 | +-------------+ 1 row in set (0.000 sec)
 
  | 
 
count(具体字段):表示统计该字段下所有不为NULL的元素的总数
count(*):统计表当中的总行数(只要有一行数据,count++)。
第三点:分组函数不能直接使用在where子句中。
1 2
   | MariaDB [hello]> select ename,sal from emp where sal >min(sal); ERROR 1111 (HY000): Invalid use of group function
 
  | 
 
为什么会报错呢?(讲完分组查询group by之后会讲)
因为分组函数在使用的时候必须先分组才能使用,当where执行的时候还没有分组,因此where后面不能出现分组函数。
疑问追加:
select sum(sal) from emp;
这个没有进行分组,为什么sum()函数又可以使用啦?
因为select在group by之后执行(详情见day08)。
第四点:所有的分组函数可以组合起来一起用
1 2 3 4 5 6 7
   | MariaDB [hello]> select sum(sal),min(sal),max(sal),avg(sal),count(*) from emp; +----------+----------+----------+-------------+----------+ | sum(sal) | min(sal) | max(sal) | avg(sal)    | count(*) | +----------+----------+----------+-------------+----------+ | 29025.00 |   800.00 |  5000.00 | 2073.214286 |       14 | +----------+----------+----------+-------------+----------+ 1 row in set (0.001 sec)
 
  |