mysql-5-aggregation

#2、分组函数
/*
分组函数/聚合函数:传入一组值,经过统计处理,得到一个输出值
sum, avg, max, min, count
*/

USE myemployees;

#简单使用
SELECT sum(salary), avg(salary), max(salary), min(salary)
FROM employees;

#参数支持类型
#sum, avg:数值型;忽略NULL
#max, min, count:数值型、字符型均可;忽略NULL

#和distinct搭配
SELECT sum(DISTINCT salary), sum(salary)
FROM employees;

SELECT max(DISTINCT salary)
FROM employees;

SELECT count(DISTINCT department_id), count(department_id)
FROM employees;


#统计表的总行数(两种方式)
SELECT count(*) FROM employees;  # 在MyISAM引擎下,效率更高
SELECT count(1) FROM employees;


#和分组函数一同查询的字段有限制


#查询员工表中的最大入职时间和最小入职时间的相差天数
SELECT datediff(max(hiredate), min(hiredate))
FROM employees;


# 案例:查询部门编号为90的员工个数
SELECT count(*) AS num
FROM employees
WHERE department_id = 90;

  

posted @ 2020-07-07 16:23  王朝君BITer  阅读(161)  评论(0编辑  收藏  举报