相关子查询在这边的例子,其实是我们只针对同一个部门或者同一个客户作为子查询的,而非针对所有员工和所有客户的数据。比如筛选员工工资高于他们部门的工资,而非高于整个公司的平均工资,筛选客户的某些高于他所有发票平均金额的发票,而非高于所有顾客平均发票额的发票。
1.
先看看employees这张表,节选,你看部门1有四个人,我们是要选出average in their office,而不是整个公司的平均值
select *
from employees e
where salary>
(select avg(salary) #(同一个部门的平均工资)
from employees
where office_id=e.office_id) #同一个部门office
最终返回11条记录
2.练习
答案:
select *
from invoices i
where invoice_total>(
select avg(invoice_total)
from invoices
where client_id=i.client_id
)