#分组函数
/*
功能:做统计使用,又称为统计函数,聚合函数,组函数
分类:sum,avg,max,min,count计算个数
特点:
1.sum,avg 用于处理数值型。max,min,count 可以处理任何类型
2.所有分组函数都忽略null
3.和distinct搭配
4.count 函数
5.和分组函数一同查询的字段要求是group by后的字段
*/
#1.简单使用
SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM employees;
SELECT MAX(salary) FROM employees;
SELECT MIN(salary) FROM employees;
SELECT COUNT(salary) FROM employees;
SELECT SUM(salary) 总计,AVG(salary) 平均,MAX(salary) 最大,MIN(salary) 最小,COUNT(salary) 计数
FROM employees;
SELECT ROUND(AVG(salary), 2) 平均
FROM employees;
#2.是否忽略null
SELECT 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;
#3.和distinct搭配
SELECT SUM(DISTINCT salary) 去重后的年薪和, SUM(salary) 年薪和
FROM employees;
SELECT COUNT(DISTINCT salary) 去重后年薪数目, COUNT(salary) 年薪数目
FROM employees;
#4.count函数的详细介绍
#统计行/个数
SELECT COUNT(*) FROM employees;
SELECT COUNT(1) FROM employees;
/*
效率:
MYISAM 存储引擎下,COUNT(*)的效率更高
INNODB 存储引擎下,COUNT(*)和COUNT(1)效率相当,但是都比count(字段)高一些
*/
#案例:查询员工表中最大入职时间和最小入职时间相差天数
SELECT DATEDIFF('2020-1-1', '2019-12-30') 相差天数; #DATEDIFF 求相差天数
SELECT DATEDIFF(MAX(`hiredate`), MIN(`hiredate`)) 相差天数
FROM employees;
#案例:查询部门编号为90的员工个数
SELECT COUNT(*) 个数
FROM employees
WHERE `department_id`=90;
mysql——分组函数
最新推荐文章于 2024-09-21 13:12:47 发布