组函数:
——类型和语法
——使用AVG,和,MIN,马克斯,计数
——组函数使用不同的关键字
——组函数中NULL值
分组函数:作用于一组数据,并对一组数据返回一个值
组函数类型
- <李>
AVG平均值
李> <李>数统计值
李> <李>MAX最大值
李> <李>最小最小值
李> <李>和合计
李> <李>STDDEV标准差
李> <李>方差方差
李>
组函数语法:
选择group_function(列),…from table [where condition] [order by column];
可以对数值型数据使用 AVG 和 SUM 函数
1、查询job_id为REP的 平均工资,最高工资,工资总和
select avg(salary),max(salary),min(salary),sum(salary) from employees where job_id like '%REP%';
可以对数值型、字符型和日期型使用 MIN 和 MAX 函数
2、查询入职时最短和最长时间
select min(hire_date),max(hire_date) from employees;
1、统计一下department_id 为50的部门有多少人
select count(*) from employees where department_id=50;
2、如果有空值不会被计算进去
select count(commission_pct) from employees where department_id=80;
3、显示 EMPLOYEES 表中不同的部门数
select count(distinct department_id) from employees;
组函数忽略空值
1、统计一下提成
select avg(commission_pct) from employees;
2、将所有的人都统计进来
select avg(nvl(commission_pct,0)) from employees;
可以使用GROUP BY 子句将表中的数据分成若干组.李李
> <>group by后面不能使用列别名,选择后面有限制。
1、求出EMPLOYEES中各个部门的平均工资
select department_id,avg(salary) from employees group by department_id order by department_id;
2、包含在 GROUP BY 子句中的列不必包含在SELECT 列表中。
select sum(salary) from employees group by job_id;
3、进行多组分列,按照部门和工作进行分组得到分组后工资的和
select department_id,job_id,sum(salary) from employees group by department_id,job_id order by department_id;
SELECT 列表中的列或表达式,未包含在组函数中的列,都必须包含于GROUP BY 子句中
错误:
select department_id, count(last_name) from employees;
或
select department_id, job_id, count(last_name) from employees group by department_id;
也就是说必须把department_id 和job_id 加入到group by 中
正确:
select department_id, count(last_name) from employees group by department_id;
或
select department_id, job_id, count(last_name) from employees group by department_id,job_id;
不能使用 WHERE 子句来过滤组
错误:
select department_id, avg(salary) from employees where avg(salary)> 8000 group by department_id;
使用在子句过滤分组条件: