一、有5个分组函数
MAX(expr)
MIN(expr)
SUM(expr)
AVG(expr)
COUNT(expr)
最大最小值只能操作
平均值与求和的只能传数值型
分组函数忽略null计算
select count(comm) from emp
select avg(ifnull(comm,0)) from emp
查询员工表中一共有几种岗位类型(去重,distinct)
select count(DISTINCT job)
from emp
注意:
使用分组函数时有严格限制,select子句后面不能再随意写,在group by后出现的才在select后面写,否则语义混乱
分组后条件在having后写
where后不能用分组函数,不能有列别名
oracle中要求select后的列(除分组函数项外)都要写在group by后面,mysql中没有这个要求
--查询每个部门的平均工资,1500以下的员工不算
select deptno,avg(sal)
from emp
where sal>=1500
group by deptno
二、select语句执行过程
书写顺序:select from where group by having order by limit
执行顺序:from where group by having select order by limit
别名是在 where中不可以使用,分组函数要使用别名命名(在别处查询时方便使用,否则会被认为是函数)
不分组不允许单独使用having
三、子查询(嵌套查询)
(无子查询时查比clark工资高的员工信息,如下)
select e.*
from emp e
join emp c
on c.ename='clark'
where e.sal>c.sal
查询不是上级的员工信息--注意null值得影响
select * from emp where empno not in (select mgr from emp where mgr is not null)
--查询部门人数大于所有部门平均人数的部门编号,部门名称,部门人数
-查出每组平均人数select renshu from (select count(empno) renshu from emp group by deptno)
-select d.deptno,dname,count(empno)
from emp e
join dept d
on e.deptno=d
group by e.deptno
having count(empno)>(select renshu from (select count(empno) renshu from emp group by deptno))
--将20部门员工工资上涨10部门平均工资
-update emp set sal=sal+(select avg(sal) from emp where deptno=10) where deptno=20
网友评论