常见函数之分组函数案例
#二、分组函数 /* 功能:用作统计使用,又称为聚合函数或统计函数或组函数 分类: sum求和、avg平均值、max最大值、min最小值、count计算个数 特点: 1.sum、avg一般用于处理数值型 max、min、count可以处理任何类型 2.以上分组函数都忽略null值 3.可以和distinct搭配去重的运算 4、COUNT函数的单独介绍 一般使用count(*) 统计函数 5、和分组函数一同查询的字段 要求是group BY 后的字段 */ #1、简单的使用 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; #2.参数支持哪些类型 SELECT SUM(last_name),avg(last_name) FROM employees; SELECT COUNT(last_name) FROM employees; SELECT MAX(last_name) FROM employees; SELECT MAX(hiredate),MIN(hiredate) FROM employees; #3、忽略null SELECT SUM(commission_pct),avg(commission_pct),SUM(commission_pct)/35 FROM employees; SELECT min(commission_pct),max(commission_pct) FROM employees; #4、和distinct搭配 SELECT SUM(DISTINCT salary),SUM(salary) FROM employees; SELECT COUNT(DISTINCT salary),COUNT(salary) FROM employees; #5、count函数的详细介绍 SELECT COUNT(salary) FROM employees; #统计函数 SELECT COUNT(*) FROM employees; SELECT COUNT(1) FROM employees; #效率: MYISAM 存储引擎下, count(*)的效率高 INNODB 存储引擎下,count(*)和count(1)的效率差不多 #6、和分组函数一同查询的字段有限制 SELECT avg(salary),employee_id FROM employees; #1.查询公司员工工资的最大值,最小值,平均值,总和 SELECT MAX(salary) mx,MIN(salary) mi,round(avg(salary),2) av,SUM(salary) sm FROM employees; #2.查询员工表中的最大入职时间和最小入职时间的相差天数(DIFFRENCE) SELECT datediff(max(hiredate),MIN(hiredate)) diffrence FROM employees; #3.查询部门编号为90的员工个数 SELECT Count(*) FROM employees WHERE department_id=90
本文来自博客园,作者:自律即自由-,转载请注明原文链接:https://www.cnblogs.com/deyo/p/13237594.html