用作统计使用,又称为聚合函数或统计函数或组函数
sum 求和、avg 平均值、max 最大值 、min 最小值 、count 计算个数
(1)sum、avg一般用于处理数值型;max、min、count可以处理任何类型;
(2)以上分组函数都忽略null值;
(3)可以和distinct搭配实现去重的运算;
(1)一般使用count(*)用作统计行数;
(2)和分组函数一同查询的字段要求是group by后的字段
SELECT SUM(salary) FROM employees;#一般适用于数值型
SELECT AVG(salary) FROM employees;#一般适用于数值型
SELECT MIN(salary) FROM employees;#适用于数值、字符等,即可比较的都适用
SELECT MAX(salary) FROM employees;#适用于数值、字符等,即可比较的都适用
SELECT COUNT(salary) FROM employees;#适用任何类型
SELECT SUM(salary) 和,AVG(salary) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT(salary) 个数
FROM employees;
SELECT SUM(salary) 和,ROUND(AVG(salary),2) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT(salary) 个数
FROM employees;
SELECT SUM(last_name) ,AVG(last_name) FROM employees;#不支持字符型
SELECT SUM(hiredate) ,AVG(hiredate) FROM employees;
SELECT MAX(last_name),MIN(last_name) FROM employees;
SELECT MAX(hiredate),MIN(hiredate) FROM employees;
SELECT COUNT(commission_pct) FROM employees;
SELECT COUNT(last_name) FROM employees;
SELECT SUM(commission_pct) ,AVG(commission_pct),SUM(commission_pct)/35,SUM(commission_pct)/107 FROM employees;
SELECT MAX(commission_pct) ,MIN(commission_pct) FROM employees;
SELECT COUNT(commission_pct) FROM employees;
SELECT commission_pct FROM employees;
SELECT SUM(DISTINCT salary),SUM(salary) FROM employees;
SELECT COUNT(DISTINCT salary),COUNT(salary) FROM employees;
SELECT COUNT(salary) FROM employees;
SELECT COUNT(*) FROM employees;
SELECT COUNT(1) FROM employees;
#效率:
#MYISAM存储引擎下,COUNT(*)的效率高
#INNODB存储引擎下,COUNT(*)和COUNT(1)的效率差不多,比COUNT(字段)要高一些
SELECT AVG(salary),employee_id FROM employees;
1、查询员工表中的最大入职时间和最小入职时间的相差天数,DATEDIFF---功能为第一个参数减去第二个参数
SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) FROM employees;
SELECT DATEDIFF(CURDATE(),'1995-12-3');