一、分组
分组: group by , 将符合条件的记录 进一步的分组
过滤组:having, 过滤组信息 ,表达式同where 一致
1.1结构
现在的结构如下
select distinct *| 字段 | 表达式 | 函数| as 别名
from 数据源 别名
where 行过滤条件
group by 分组
having 组过滤信息
order by 排序字段 asc | desc ;
1.2执行流程
执行流程 : from -> where -> group by -> having -> select -> order by
1.3注意事项
group by : 分组
1)、select出现分组函数,就不能使用 非分组信息,可以使用group by 字段
2)、group by字段 可以不出现 select 中 ,反之select 除组函数外的,其他字段必须出现在group by中
having : 过滤组
1)、where : 过滤行记录,不能使用组函数
2)、having : 过滤组 可以使用组函数
where中不能使用字段别名,不能使用组函数,因为执行流程问题
1.4例子
-- 求出每个部门的平均工资
select deptno,avg(sal) from emp group by deptno;
-- 找出20部门和30部门的最高工资
select deptno,max(sal) from emp group by deptno;
--先过滤后分组
select deptno,max(sal) from emp where deptno in(20,30) group by deptno;
--先分组后过滤
select deptno,max(sal) from emp group by deptno having deptno in(20,30);
-- 求出10和20部门部门的哪些工资高于1000的员工的平均工资
select avg(sal) from emp where sal>1000 and deptno in(10,20) group by deptno