五、分组函数
常用分组函数:types of group functions
avg 求平均值
count 返回非空行的总行数 (可以配合distinct使用,返回去重复后的行数)
max 最大数
min 最小数
stddev 标准差
sum 求和
variance 差额
分组函数用法:
select column,group_function(column),.... from table
where condition
group by column
having condition
order by column;
select avg(sal),max(sal),min(sal),sum(sal) from emp
where deptno=10;
查看10部门的平均,最大,最小,总和,的薪水
select count(ename) from emp ;
返回emp表的名字的总行数
select count(distinct deptno) from emp;
返回去重复后的部门总行数
创建分组数据group by 语法
1、使用group by 可以把表的行分割成多个小组
2、非分组列出现在select列表中必须使用group by
3、分组列也可以不出现在select列表之中
易错点:
1、where字句中不能使用分组函数,可以在group by前调用其他函数限制
2、having用来限制分组函数条件
having语法:
1、行被分组
2、条件为分组函数
3、匹配having的结果被显示
SQL> select deptno,job,avg(sal) from emp 查看部门、工作为组的平均薪水
2 where sal > 1000 只查看大于1000的薪水
3 group by deptno,job 分组函数
4 having avg(sal) > 1500 只显示大于1500的平均薪水
5 order by avg(sal) desc; 按照平均薪水降序排序
DEPTNO JOB AVG(SAL)
---------- --------- ----------
10 PRESIDENT 5000
20 ANALYST 3000
20 MANAGER 2975
30 MANAGER 2850
10 MANAGER 2450
嵌套:nesting group functions
max(avg(sal))
1、一般使用两次就没办法继续嵌套了
SQL> select max(avg(sal)) from emp
2 group by deptno;
MAX(AVG(SAL))
-------------
2916.66667