多表查询 子查询 与分组函数学习笔记

多表查询

 --查询部门编号,部门名称和其所处的地区的名称 和所在的城市(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;

查询部门编号,部门名称和其所处的地区的名称 和所在的城市(2表内连接)

  --查询员工的工资等级 (非等值判断)
    --[介于两者 (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

平均工资高于8000的部门

子查询

--谁的工资比 Abel 高?
    --1.查询 Abel 的工资
    select salary from employees where last_name = 'Abel';

Abel的工资

  --2.查询比11000的工资要高的人的记录
    select * from employees where salary > 11000;

比工资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';


更多技术分享,请关注公众号:XC_Message

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值