一、统计查询
count(属性名),max(属性名),min(属性名): 适用于:数值,字符,日期
avg(属性名),sum(属性名):只用于数值
- 聚集函数统计时忽略空值
- 统计时如果希望忽略重复值,则需要在属性前加distinct
- where中不能使用聚集函数
1.工资的平均值
select avg(salary)
from emp
2.提成的平均值(自动会忽略空值)
select avg(comm_pct)
from emp
3.有多少种提成的值( count:查询属性种有多少个值,不是种,重复值也算)
select count(comm_pct)--错误
from emp
select count(distinct comm_pct)
from emp
4.count(*) : 统计结果有多少行
select count(*) from emp
二、分组查询 :
- group by 属性名1,属性名2,.......
- 当group by后有多个属性,表示将查询结果按照属性从左到右的顺序一次分组
- group by 要写在where之后,order by 之前
1.每个部门的平均工资
select dept_id avg(salary)
from emp
group by dept_id
2.查询2号部门的平均工资
select dept_id avg(salary)
from emp
where dept_id=2;
select dept_id avg(salary)
from emp
where dept_id=2;
如果select子句的属性列表中有聚集函数,则其他属性要么出现在gropy by中要么出现在聚集函数中
3.每个部分每个职位的平均工资
select dept_id,title,avg(salary)
from emp
group by dept_id,title
order by dept_id;
4.查询部门平均工资高于1000的部门及其平均工资
having:用于对分组的筛选,只能跟在group by之后不能单独使用,在分组之后完成筛选
where:用于对元组的筛选
select dept_id,avg(salary)
from emp
where avg(salary)>1500 错误
group by dept_id;
select dept_id,avg(salary)
from emp
group by dept_id
having avg(salary)>1500 ;
完整的select语句顺序写法:
select .....
from...
where
group by
having
order by
三、子查询
1.查询工资最低的员工
select *
from emp
where salary = min(salary) --错误 where 不能使用聚集函数
select *
from emp
where salary =(select min(salary) from emp)
子查询最好不用order by语句
非关联子查询:子查询先于父查询执行,只执行一次
2.查询职位和Molly相同的员工
select *
from emp
where title =(select title from emp where name='Molly')
and name <>'Molly' ×
select *
from emp e1,emp e2
where e1.title=e2.title and e2.name ='Molly' and e1.name<>'Molly'
当有两个Molly时,子查询会报错
=,>,<>=,<=,<>单值比较运算符只能引导返回值为单行的子查询
select *
from emp
where title in(select title from emp where name='Molly')
and name <>'Molly' √
select e1.*
from emp e1 inner join emp e2
on e1.title=e2.title
where e2.name='Molly' and e1.name<>'Molly'
2.比2号部门所有员工工资都高的员工
select *
from emp
where salary >(select salary from emp where dept_id=2) ×
第一种:
select *
from emp
where salary >all(select salary from emp where dept_id=2)
第二种:
select *
from emp
where salary >(select max(salary) from emp where dept_id=2)
3.谁是领导
select *
from emp
where id in select manager_id from emp
4.不是领导
select *
from emp
where id not in (select manager_id from emp) ×
select *
from emp
where id not in (select manager_id
from emp where manager_id is not null )
5.部门平均工资比2号部门平均工资高的部门编号和平均工资
select dept_id,avg(salary)
from emp
where avg(salary)>(select avg(salary) from emp where dept_id =2)
group by dept_id ×
select dept_id,avg(salary)
from emp
group by dept_id
having avg(salary)>(select avg(salary) from emp where dept_id =2)
Union all:保留重复元组
Union:去除结果中重复元组
交:intersect
差:except/minus
分页查询
limit 写在order by之后
limit n,m
n表示从第几个开始取,下标从0开始。n值可以省略,默认表示开始从第0个开始取
m表示取多少个
查询工资最高的前10名:
select *
from emp
order by salary desc
limit 0,10
交叉表查询
派生表查询