多表查询
--查询部门编号,部门名称和其所处的地区的名称 和所在的城市(2表内连接)
select d.department_id,d.department_name,l.location_id,l.street_address,l.city
from departments d,locations l
where d.location_id = l.location_id;
--查询员工的工资等级 (非等值判断)
--[介于两者 (A和B)之间的范围 ]:between (A) and (B)
select e.last_name , e.salary , j.grade_level
from employees e , job_grades j
where e.salary between j.lowest_sal and j.highest_sal;
--查询员工名称为grant的薪水,经理编号,经理名称,经理的薪水(自连接查询)
select e.employee_id,e.last_name,e.salary as "员工薪水",m.manager_id,m.last_name,m.salary as "经理薪水"
from employees e , employees m
where e.manager_id = m.employee_id
and lower(e.last_name) = 'grant';
分组函数
--[平均值]:avg() avg 将自动过滤为空的字段
--求员工的平均薪水
select avg(salary) from employees;
--[计数]:count()
--计算员工表中有多少条记录
select count(*),count(1),count(2) from employees;
--计算最大值、最小追、求和
select max(salary) as "最高薪水",min(salary) as "最低薪水",sum(salary) as "总薪水"
from employees;
--求平均值空值的问题
select avg(commission_pct) as "平均奖金率(平均函数所求)",sum(commission_pct)/count(*) as "平均奖金率(总奖金率/总人数)",count(commission_pct) as "拥有奖金率的人数",count(*) as "总人数"
from employees;
--[去除重复]:distinct
----计算多少个部门
select count(distinct department_id) from employees;
--查看所有部门编号
select distinct department_id from employees;
--查询部门编号是10 50 70 80 100的平均工资高于8000的部门
select department_id , job_id , avg(salary)
from employees
where department_id in (10,50,70,80,100)
group by department_id,job_id
having avg(salary) > 8000
order by department_id;
--根据where中的条件来查询并分组,查询出来的结果用having来过滤,最后排序
--select --> from --> where --> group by ---> having ---> order by
子查询
--谁的工资比 Abel 高?
--1.查询 Abel 的工资
select salary from employees where last_name = 'Abel';
--2.查询比11000的工资要高的人的记录
select * from employees where salary > 11000;
--合并
select * from employees where salary >
(select salary from employees where last_name = 'Abel');
--返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工的员工号、姓名、job_id 以及salary
select employee_id ,last_name ,job_id ,salary
from employees
where salary < all(select salary from employees where lower(job_id) = 'it_prog')
and lower(job_id) <> 'it_prog';